﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Text.RegularExpressions;


public partial class Order_OrderDetail : System.Web.UI.Page, ICallbackEventHandler
{
    string result = "";

    #region 属性




    private string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"].ToString() : "";
        }
    }

    private DataSet DstOrderMainInfo
    {
        get
        {
            DataSet dst = null;
            if (ViewState["DstOrderMainInfo"] != null)
            {
                dst = (DataSet)ViewState["DstOrderMainInfo"];
            }
            return dst;
        }
        set
        {
            ViewState["DstOrderMainInfo"] = value;
        }
    }

    private DataTable DataTableOrderDetail
    {
        get
        {
            DataTable dTableOrderDetail = null;
            if (ViewState["DataTableOrderDetail"] != null)
            {
                dTableOrderDetail = (DataTable)ViewState["DataTableOrderDetail"];
            }
            return dTableOrderDetail;
        }
        set
        {
            ViewState["DataTableOrderDetail"] = value;
        }
    }

    private DataTable DataTableOrderPayDetail
    {
        get
        {
            DataTable dTableOrderPayDetail = null;
            if (ViewState["DataTableOrderPayDetail"] != null)
            {
                dTableOrderPayDetail = (DataTable)ViewState["DataTableOrderPayDetail"];
            }
            return dTableOrderPayDetail;
        }
        set
        {
            ViewState["DataTableOrderPayDetail"] = value;
        }
    }

    private List<Model.PAYTYPE> PayType
    {
        get
        {
            List<Model.PAYTYPE> payType = null;
            if (ViewState["PayType"] != null)
            {
                payType = (List<Model.PAYTYPE>)ViewState["PayType"];
            }
            return payType;
        }
        set
        {
            ViewState["PayType"] = value;
        }
    }

    private bool IsUseColorSize
    {
        get
        {
            return new BLL.SYSPARAM().GetProductUpDownColorSizeConfig();
        }
    }

    private bool SelectProductConfig
    {
        get
        {
            return new BLL.SYSPARAM().GetSelectProductConfig();
        }
    }

    private bool IsRestockUseColorSize
    {
        get
        {
            return new BLL.SYSPARAM().GetRestockColorSizeConfig();
        }
    }

    private bool IsUseServiceStation
    {
        get
        {
            return new BLL.SYSPARAM().GetServiceStationConfig();
        }
    }

    private string OrderStateTypeCode
    {
        get
        {
            string orderStateTypeCode = "";
            if (ViewState["OrderStateTypeCode"] != null)
            {
                orderStateTypeCode = ViewState["OrderStateTypeCode"].ToString();
            }
            return orderStateTypeCode;
        }
        set
        {
            ViewState["OrderStateTypeCode"] = value;
        }
    }

    private string PhoneStr;

    private decimal SumZF = 0.00M;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("400101");
        if (!IsPostBack)
        {
            hidUser.Value = Share.UserValue(0);
            hidpostback.Value = "0"; //如果是第一次加载,那么订单的物流费用,不动态计算


            hidFreeWL.Value = BLL.Common.GetFreeStandard().ToString();
            BindDataListOrderMain();
            BindReceiveAddress();
            BindOrderDetail();
            BindPayDetail();
            //BindDataListCoupon();
            SetPropertyOfButtons();
            BindDropProvince();
            GetPayType();
            BindOrderNote();

            btnSave.Attributes.Add("onclick", "Mask();");
            //btnAudit.Attributes.Add("onclick", "Mask();");
            btnAntiAudit.Attributes.Add("onclick", "Mask();");
            btnFinancialAffairsAudit.Attributes.Add("onclick", "Mask();");
            btnFinancialAffairsAntiAudit.Attributes.Add("onclick", "if(CheckConfirm()) Mask();");


            Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(Request.QueryString["code"].ToString().Trim());//获取订单主表
            hdPrintFlag1.Value = order.ORDER_PRINT.ToString();
            hdPrintFlag2.Value = order.ORDER_TPRINT.ToString();


        }
        else
        {
            hidpostback.Value = "1";
        }
    }

    #region 订单主表控件绑定及相关操作



    private void BindDataListOrderMain()
    {
        this.DstOrderMainInfo = new BLL.ORDERDOC().GetOrderInfoByOrderId(this.Code);
        dlistOrderMain.DataSource = this.DstOrderMainInfo;
        dlistOrderMain.DataBind();
        hidCity.Value = this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_CITY"].ToString();
        hidCustomerId.Value = this.DstOrderMainInfo.Tables[0].Rows[0]["CustomerCode"].ToString();
        StringBuilder receiveAddress = new StringBuilder();
        receiveAddress.Append(this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_GETER"].ToString() + "$");
        receiveAddress.Append(this.DstOrderMainInfo.Tables[0].Rows[0]["order_Province"].ToString() + "$");
        receiveAddress.Append(this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_CITY"].ToString() + "$");
        receiveAddress.Append(this.DstOrderMainInfo.Tables[0].Rows[0]["order_area"].ToString() + "$");
        receiveAddress.Append(this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_GETADDRESS"].ToString() + "$");
        receiveAddress.Append(this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_GETPOSTCODE"].ToString() + "$");
        receiveAddress.Append(this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_GETERPHONE1"].ToString() + "$");
        receiveAddress.Append(this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_GETERPHONE2"].ToString());
        hidReceiveAddressInfo.Value = receiveAddress.ToString();
        OrderStateTypeCode = DstOrderMainInfo.Tables[0].Rows[0]["ORDER_STATETYPECODE"].ToString();
        hidIsPayAfterReceive.Value = this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_APAY"].ToString();
        hidIsUseStationDelivery.Value = this.DstOrderMainInfo.Tables[0].Rows[0]["IsDelivery"].ToString();
        hidLocker.Value = this.DstOrderMainInfo.Tables[0].Rows[0]["ORDER_LOCKER"].ToString();
        hidLockerName.Value = this.DstOrderMainInfo.Tables[0].Rows[0]["Locker"].ToString();

        if (this.DstOrderMainInfo.Tables[0].Rows[0]["IsDelivery"].ToString() == "1")
        {
            lblServiceStationId.Text = this.DstOrderMainInfo.Tables[0].Rows[0]["BYZD4"].ToString();
            lblServiceStationName.Text = new BLL.ServiceSites().GetModel(Convert.ToInt32(this.DstOrderMainInfo.Tables[0].Rows[0]["BYZD4"].ToString())).SS_Name;
            hidServiceStationId.Value = lblServiceStationId.Text;
            hidServiceStationName.Value = lblServiceStationName.Text;
            chk1.Checked = this.DstOrderMainInfo.Tables[0].Rows[0]["BYZD6"].ToString() == "1" ? true : false;
        }
    }

    private void BindDropOrderSource(DropDownList drop)
    {
        List<Model.ORDERFROM> of = new BLL.ORDERFROM().GetAllList();
        drop.DataSource = of;
        drop.DataTextField = "OF_NAME";
        drop.DataValueField = "OF_CODE";
        drop.DataBind();
    }

    private void BindDropTraner(DropDownList drop)
    {
        List<Model.TRANER> traner = new BLL.TRANER().GetAllList(true);
        drop.DataSource = traner;
        drop.DataTextField = "TRANER_NAME";
        drop.DataValueField = "TRANER_CODE";
        drop.DataBind();
    }

    protected void dlistOrderMain_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            HtmlInputHidden hidOrderSource = (HtmlInputHidden)e.Item.FindControl("hidOrderSource");
            DropDownList dropOrderSource = (DropDownList)e.Item.FindControl("dropOrderSource");
            BindDropOrderSource(dropOrderSource);
            dropOrderSource.SelectedValue = hidOrderSource.Value;

            HtmlInputHidden hidTraner = (HtmlInputHidden)e.Item.FindControl("hidTraner");
            DropDownList dropTraner = (DropDownList)e.Item.FindControl("dropTraner");
            BindDropTraner(dropTraner);
            dropTraner.SelectedValue = hidTraner.Value;

            HtmlInputHidden hidPayAfterReceive = (HtmlInputHidden)e.Item.FindControl("hidPayAfterReceive");
            DropDownList dropPayAfterReceive = (DropDownList)e.Item.FindControl("dropPayAfterReceive");
            dropPayAfterReceive.SelectedValue = hidPayAfterReceive.Value;

            HtmlInputHidden hidCostNature = (HtmlInputHidden)e.Item.FindControl("hidCostNature");
            DropDownList dropCostNature = (DropDownList)e.Item.FindControl("dropCostNature");
            dropCostNature.SelectedValue = hidCostNature.Value;

            HtmlTableRow source = (HtmlTableRow)e.Item.FindControl("source");
            if (Share.IsExistPromoteSales == "0")
            {
                source.Visible = false;
            }
            else if (Share.IsExistPromoteSales == "1")
            {
                source.Visible = true;
            }

        }
    }

    #endregion

    #region 收货地址控件绑定及相关操作



    private void BindReceiveAddress()
    {
        dlistReceiveAddress.DataSource = new BLL.V_CUSTOMER_ADDRESS().GetCustomerReceiveAddressByCustomerId(hidCustomerId.Value);
        dlistReceiveAddress.DataBind();
    }

    protected void BindDropProvince()
    {
        List<Model.Province> provinces = new BLL.Province().GetAllList();
        Province.DataSource = provinces;
        Province.DataTextField = "ProName";
        Province.DataValueField = "ProId";
        Province.DataBind();
        ListItem item = new ListItem();
        item.Value = "-1";
        item.Text = "";
        Province.Items.Insert(0, item);
    }

    #endregion

    #region 订单明细表控件绑定及相关操作
    private void BindOrderDetail()
    {
        DataSet DST = new BLL.ORDERDETAIL().GetOrderDetailByOrderId(this.Code);
        this.DataTableOrderDetail = new BLL.ORDERDETAIL().GetOrderDetailByOrderId(this.Code).Tables[0];
        dlistOrderDetail.DataSource = this.DataTableOrderDetail;
        dlistOrderDetail.DataBind();

        hidOrderDetailCount.Value = this.DataTableOrderDetail.Rows.Count.ToString();
    }

    private void BindOrderDetail(DataTable tbl)
    {
        dlistOrderDetail.DataSource = tbl;
        dlistOrderDetail.DataBind();
    }

    private void BindDropProductColor(DropDownList dropColor, string productCode)
    {
        if (SelectProductConfig)
        {
            DataSet dstProductColor = new BLL.SHANGPIN().GetSPGG1(productCode);
            if (dropColor.Items.Count > 0)
            {
                dropColor.Items.Clear();
            }
            dropColor.Items.Add(new ListItem("", "-1"));
            foreach (DataRow dr in dstProductColor.Tables[0].Rows)
            {
                dropColor.Items.Add(new ListItem(dr["ggmc"].ToString(), dr["GGDM"].ToString()));
            }
            //dropColor.DataSource = dstProductColor;
            //dropColor.DataTextField = "ggmc";
            //dropColor.DataValueField = "ggdm";
            //dropColor.DataBind();
        }
        else
        {
            if (IsUseColorSize)
            {
                DataSet dstProductColor = new BLL.ProductUpDown().GetColorByProductIdAndIsUp(productCode);
                if (dropColor.Items.Count > 0)
                {
                    dropColor.Items.Clear();
                }
                dropColor.Items.Add(new ListItem("", "-1"));
                foreach (DataRow row in dstProductColor.Tables[0].Rows)
                {
                    dropColor.Items.Add(new ListItem(row["colorName"].ToString(), row["colorCode"].ToString()));
                }
                //dropColor.DataSource = dstProductColor;
                //dropColor.DataTextField = "colorName";
                //dropColor.DataValueField = "colorCode";
                //dropColor.DataBind();
            }
            else
            {
                DataSet dstProductColor = new BLL.SHANGPIN().GetSPGG1(productCode);
                if (dropColor.Items.Count > 0)
                {
                    dropColor.Items.Clear();
                }
                dropColor.Items.Add(new ListItem("", "-1"));
                foreach (DataRow row in dstProductColor.Tables[0].Rows)
                {
                    dropColor.Items.Add(new ListItem(row["ggmc"].ToString(), row["ggdm"].ToString()));
                }
                //dropColor.DataSource = dstProductColor;
                //dropColor.DataTextField = "ggmc";
                //dropColor.DataValueField = "ggdm";
                //dropColor.DataBind();
            }
        }

    }

    private void BindDropProductSize(DropDownList dropSize, string productCode, string colorCode)
    {
        if (SelectProductConfig)
        {
            DataSet dstProductSize = new BLL.SHANGPIN().GetSPGG2(productCode);
            if (dropSize.Items.Count > 0)
            {
                dropSize.Items.Clear();
            }
            dropSize.Items.Add(new ListItem("", "-1"));
            foreach (DataRow row in dstProductSize.Tables[0].Rows)
            {
                dropSize.Items.Add(new ListItem(row["ggmc"].ToString(), row["ggdm"].ToString()));
            }
            //dropSize.DataSource = dstProductSize;
            //dropSize.DataTextField = "ggmc";
            //dropSize.DataValueField = "ggdm";
            //dropSize.DataBind();
        }
        else
        {
            if (IsUseColorSize)
            {
                DataSet dstProductSize = new BLL.ProductUpDown().GetSizeByProductIdAndColorAndIsUP(productCode, colorCode);
                if (dropSize.Items.Count > 0)
                {
                    dropSize.Items.Clear();
                }
                dropSize.Items.Add(new ListItem("", "-1"));
                foreach (DataRow row in dstProductSize.Tables[0].Rows)
                {
                    dropSize.Items.Add(new ListItem(row["sizeName"].ToString(), row["sizeCode"].ToString()));
                }
                //dropSize.DataSource = dstProductSize;
                //dropSize.DataTextField = "sizeName";
                //dropSize.DataValueField = "sizeCode";
                //dropSize.DataBind();
            }
            else
            {
                DataSet dstProductSize = new BLL.SHANGPIN().GetSPGG2(productCode);
                if (dropSize.Items.Count > 0)
                {
                    dropSize.Items.Clear();
                }
                dropSize.Items.Add(new ListItem("", "-1"));
                foreach (DataRow row in dstProductSize.Tables[0].Rows)
                {
                    dropSize.Items.Add(new ListItem(row["sizeName"].ToString(), row["sizeCode"].ToString()));
                }
                //dropSize.DataSource = dstProductSize;
                //dropSize.DataTextField = "ggmc";
                //dropSize.DataValueField = "ggdm";
                //dropSize.DataBind();
            }
        }
    }

    protected void dlistOrderDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            Label lblCode = (Label)e.Item.FindControl("lblCode");
            HtmlInputHidden hidColor = (HtmlInputHidden)e.Item.FindControl("hidColor");
            HtmlInputHidden hidSize = (HtmlInputHidden)e.Item.FindControl("hidSize");
            HtmlInputHidden hidPromotionIsUseCustomerDiscount = (HtmlInputHidden)e.Item.FindControl("hidPromotionIsUseCustomerDiscount");
            DropDownList dropColor = (DropDownList)e.Item.FindControl("dropColor");
            DropDownList dropSize = (DropDownList)e.Item.FindControl("dropSize");
            Label lblIsPresent = (Label)e.Item.FindControl("lblIsPresent");
            Label lblPreferentialMode = (Label)e.Item.FindControl("lblPreferentialMode");

            BindDropProductColor(dropColor, lblCode.Text);
            if (hidColor.Value != "")
            {
                dropColor.SelectedValue = hidColor.Value;
            }
            BindDropProductSize(dropSize, lblCode.Text, dropColor.SelectedValue);
            if (hidSize.Value != "")
            {
                dropSize.SelectedValue = hidSize.Value;
            }

            HtmlTableCell PromoteSalesColumn = (HtmlTableCell)e.Item.FindControl("PromoteSalesColumn");
            TextBox txtQuantity = (TextBox)e.Item.FindControl("txtQuantity");
            TextBox txtDiscount = (TextBox)e.Item.FindControl("txtDiscount");
            HtmlInputHidden hidIsPresent = (HtmlInputHidden)e.Item.FindControl("hidIsPresent");
            Button btnPromotionSales = (Button)e.Item.FindControl("btnPromotionSales");
            HtmlInputHidden hidPreferentialMode = (HtmlInputHidden)e.Item.FindControl("hidPreferentialMode");
            Button btnSelectPresent = (Button)e.Item.FindControl("btnSelectPresent");
            if (Share.IsExistPromoteSales == "0")
            {
                PromoteSalesColumn.Visible = false;
            }
            else if (Share.IsExistPromoteSales == "1")
            {
                PromoteSalesColumn.Visible = true;
                if (hidIsPresent.Value == "1")
                {
                    txtQuantity.Enabled = false;
                    txtDiscount.Enabled = false;
                    btnPromotionSales.Visible = false;
                    lblIsPresent.Text = " <礼品> ";
                }
                else if (hidIsPresent.Value == "0")
                {
                    if (hidPreferentialMode.Value == "-1")
                    {
                        btnPromotionSales.Enabled = false;
                    }
                    else if (hidPreferentialMode.Value == "0")
                    {
                        btnPromotionSales.Enabled = true;
                    }
                    else if (hidPreferentialMode.Value == "1" || hidPreferentialMode.Value == "2" || hidPreferentialMode.Value == "3")
                    {
                        btnPromotionSales.Enabled = false;
                        if (hidPreferentialMode.Value == "3")
                        {
                            btnSelectPresent.Visible = true;
                        }

                        if (hidPromotionIsUseCustomerDiscount.Value == "0")
                        {
                            txtDiscount.Enabled = false;
                        }
                        else if (hidPromotionIsUseCustomerDiscount.Value == "0")
                        {
                            txtDiscount.Enabled = false;
                        }


                        lblPreferentialMode.Text = " <" + BLL.Common.GetYHFSName(hidPreferentialMode.Value) + "> ";
                    }
                }
            }
        }
        else if (e.Item.ItemType == ListItemType.Header)
        {
            HtmlTableCell PromoteSalesColumn = (HtmlTableCell)e.Item.FindControl("PromoteSalesColumn");
            if (Share.IsExistPromoteSales == "0")
            {
                PromoteSalesColumn.Visible = false;
            }
            else if (Share.IsExistPromoteSales == "1")
            {
                PromoteSalesColumn.Visible = true;
            }
        }
    }

    protected void dlistOrderDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "del")
        {
            FillValueIntoOrderDetailDataTable(this.DataTableOrderDetail);

            BindOrderDetail(new BLL.ORDERDETAIL().SubDataRowFromDataTable(this.DataTableOrderDetail, e.Item.ItemIndex));

            hidOrderDetailCount.Value = this.DataTableOrderDetail.Rows.Count.ToString();
        }
        else if (e.CommandName.ToLower() == "promotionsales")
        {
            string[] selectedPromotionValue = hidSelectedPromotion.Value.Split('$');
            if (selectedPromotionValue.Length == 7)
            {
                HtmlInputHidden hidPreferentialMode = (HtmlInputHidden)e.Item.FindControl("hidPreferentialMode");
                HtmlInputHidden hidPromotionId = (HtmlInputHidden)e.Item.FindControl("hidPromotionId");
                HtmlInputHidden hidSprice = (HtmlInputHidden)e.Item.FindControl("hidSprice");
                HtmlInputHidden hidAprice = (HtmlInputHidden)e.Item.FindControl("hidAprice");
                HtmlInputHidden hidPromotionIsUseCustomerDiscount = (HtmlInputHidden)e.Item.FindControl("hidPromotionIsUseCustomerDiscount");
                HtmlInputHidden hidPromotionOffAmt = (HtmlInputHidden)e.Item.FindControl("hidPromotionOffAmt");
                TextBox txtDiscount = (TextBox)e.Item.FindControl("txtDiscount");
                Label lblAamt = (Label)e.Item.FindControl("lblAamt");
                Label lblAprice = (Label)e.Item.FindControl("lblAprice");
                TextBox txtQuantity = (TextBox)e.Item.FindControl("txtQuantity");
                Button btnPromotionSales = (Button)e.Item.FindControl("btnPromotionSales");
                Button btnSelectPresent = (Button)e.Item.FindControl("btnSelectPresent");
                Label lblPreferentialMode = (Label)e.Item.FindControl("lblPreferentialMode");

                switch (selectedPromotionValue[1])
                {
                    case "1":
                        hidPreferentialMode.Value = "1";
                        hidPromotionId.Value = selectedPromotionValue[0];
                        //hidSprice.Value = String.Format("{0:0.00}", Convert.ToDecimal(hidSprice.Value) * Convert.ToDecimal(selectedPromotionValue[2]));
                        //hidAprice.Value = String.Format("{0:0.00}", Convert.ToDecimal(hidSprice.Value) * Convert.ToDecimal(txtDiscount.Text) * Convert.ToDecimal(selectedPromotionValue[2]));
                        //lblAprice.Text = String.Format("{0:0.00}", Convert.ToDecimal(hidSprice.Value) * Convert.ToDecimal(txtDiscount.Text) * Convert.ToDecimal(selectedPromotionValue[2]));
                        //lblAamt.Text = String.Format("{0:0.00}", Convert.ToDecimal(hidSprice.Value) * Convert.ToDecimal(txtDiscount.Text) * Convert.ToDecimal(selectedPromotionValue[2]) * Convert.ToDecimal(txtQuantity.Text));
                        hidPromotionIsUseCustomerDiscount.Value = selectedPromotionValue[6];
                        hidPromotionOffAmt.Value = selectedPromotionValue[5];
                        if (hidPromotionIsUseCustomerDiscount.Value == "1")
                        {
                            txtDiscount.Text = String.Format("{0:0.00}", Convert.ToDecimal(txtDiscount.Text) * Convert.ToDecimal(selectedPromotionValue[2]));
                            txtDiscount.Enabled = false;
                        }
                        else if (hidPromotionIsUseCustomerDiscount.Value == "0")
                        {
                            txtDiscount.Text = String.Format("{0:0.00}", Convert.ToDecimal(selectedPromotionValue[2]));
                            txtDiscount.Enabled = false;
                        }
                        btnPromotionSales.Enabled = false;
                        break;
                    case "2":
                        hidPreferentialMode.Value = "2";
                        hidPromotionId.Value = selectedPromotionValue[0];
                        //hidSprice.Value = hidSprice.Value;
                        //lblAprice.Text = hidAprice.Value;
                        //lblAamt.Text = String.Format("{0:0.00}", Convert.ToDecimal(lblAprice.Text) * Convert.ToDecimal(txtQuantity.Text));
                        hidPromotionIsUseCustomerDiscount.Value = selectedPromotionValue[6];
                        hidPromotionOffAmt.Value = selectedPromotionValue[5];
                        if (hidPromotionIsUseCustomerDiscount.Value == "1")
                        {
                            txtDiscount.Enabled = false;
                        }
                        else if (hidPromotionIsUseCustomerDiscount.Value == "0")
                        {
                            txtDiscount.Text = "1.00";
                            txtDiscount.Enabled = false;
                        }
                        hidAprice.Value = String.Format("{0:0.00}", Convert.ToDecimal(hidSprice.Value) * Convert.ToDecimal(txtDiscount.Text) - Convert.ToDecimal(selectedPromotionValue[5]));

                        btnPromotionSales.Enabled = false;
                        break;
                    case "3":
                        hidPreferentialMode.Value = "3";
                        hidPromotionId.Value = selectedPromotionValue[0];
                        hidPromotionIsUseCustomerDiscount.Value = selectedPromotionValue[6];
                        hidPromotionOffAmt.Value = selectedPromotionValue[5];
                        if (hidPromotionIsUseCustomerDiscount.Value == "1")
                        {
                            txtDiscount.Enabled = false;
                        }
                        else if (hidPromotionIsUseCustomerDiscount.Value == "0")
                        {
                            txtDiscount.Text = "1.00";
                            txtDiscount.Enabled = false;
                        }
                        btnPromotionSales.Enabled = false;
                        btnSelectPresent.Visible = true;
                        btnSelectPresent.Enabled = true;
                        break;
                }
                lblPreferentialMode.Text = " <" + BLL.Common.GetYHFSName(hidPreferentialMode.Value) + "> ";
            }
        }
        else if (e.CommandName.ToLower() == "selectpresent")
        {
            Label lblCode = (Label)e.Item.FindControl("lblCode");
            HtmlInputHidden hidDetailId = (HtmlInputHidden)e.Item.FindControl("hidDetailId");
            string[] selectedPresentValue = hidSelectedPresent.Value.Split('$');
            if (selectedPresentValue.Length == 2)
            {
                DataSet dstSpecifiedPresentAmount = new BLL.CXFAD8MX1().GetSpecifiedPresentAmount(selectedPresentValue[1], selectedPresentValue[0]);
                if (dstSpecifiedPresentAmount.Tables[0].Rows.Count < 1)
                {
                    Share.Alert(this.Page, "系统无法获取到该商品的赠送礼品信息,不能再添加礼品!"); return;
                }

                FillValueIntoOrderDetailDataTable(this.DataTableOrderDetail);

                int presentAmount = 0;
                for (int i = 0; i < this.DataTableOrderDetail.Rows.Count; i++)
                {
                    if (this.DataTableOrderDetail.Rows[i]["OD_FIELD1"].ToString() == hidDetailId.Value)
                    {
                        presentAmount++;
                    }
                }

                if (presentAmount < Convert.ToInt32(dstSpecifiedPresentAmount.Tables[0].Rows[0]["SL"]))
                {
                    DataSet dstProduct = new BLL.SHANGPIN().GetProductInfoByCode(selectedPresentValue[1]);
                    if (dstProduct.Tables[0].Rows.Count == 0)
                    {
                        Share.Alert(this.Page, "系统无法获取礼品的相关信息,不能再添加礼品!"); return;
                    }
                    new BLL.ORDERDETAIL().AddDataRowToDataTable(this.DataTableOrderDetail, dstProduct.Tables[0].Rows[0]["spdm"].ToString(), 1.00M, 0.00M, dstProduct.Tables[0].Rows[0]["spmc"].ToString(), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["CA_WEIGHT"]), "1", hidDetailId.Value, selectedPresentValue[0], "");
                }
                else
                {
                    hidSelectedPresent.Value = "";
                    Share.Alert(this.Page, "您选择的礼品数已经达到了本次活动的送礼品数,不能再添加礼品!"); return;
                }


                hidSelectedPresent.Value = "";
                BindOrderDetail(this.DataTableOrderDetail);

                hidOrderDetailCount.Value = this.DataTableOrderDetail.Rows.Count.ToString();

                hidProduct.Value = "";

            }
        }
    }

    protected void btnAddProduct_Click(object sender, EventArgs e)
    {
        try
        {
            FillValueIntoOrderDetailDataTable(this.DataTableOrderDetail);

            string customerCode = ((Label)dlistOrderMain.Items[0].FindControl("lblCustomerCode")).Text;

            DataSet dstVipSet = new BLL.V_VIPSET().GetVipInfoByGKDM(customerCode);

            if (dstVipSet.Tables[0].Rows.Count == 0)
            {
                Share.Alert(this.Page, "系统无法获取该客户的折扣信息!"); return;
            }

            if (Share.IsExistPromoteSales == "1")
            {
                string[] arrayProductCode = hidProduct.Value.Split(',');
                DataSet dstProduct;
                for (int i = 0; i < arrayProductCode.Length; i++)
                {
                    dstProduct = new BLL.SHANGPIN().GetProductInfoByCode(arrayProductCode[i]);
                    if (dstProduct.Tables[0].Rows.Count == 0)
                    {
                        continue;
                    }
                    if (new BLL.CXFAD8MX1().IsExistPromotion(arrayProductCode[i]))
                    {
                        new BLL.ORDERDETAIL().AddDataRowToDataTable(this.DataTableOrderDetail, dstProduct.Tables[0].Rows[0]["spdm"].ToString(), Convert.ToDecimal(dstVipSet.Tables[0].Rows[0]["ZK"]), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["BZSJ"]), dstProduct.Tables[0].Rows[0]["spmc"].ToString(), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["CA_WEIGHT"]), "0", "", "", "0");
                    }
                    else
                    {
                        new BLL.ORDERDETAIL().AddDataRowToDataTable(this.DataTableOrderDetail, dstProduct.Tables[0].Rows[0]["spdm"].ToString(), Convert.ToDecimal(dstVipSet.Tables[0].Rows[0]["ZK"]), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["BZSJ"]), dstProduct.Tables[0].Rows[0]["spmc"].ToString(), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["CA_WEIGHT"]), "0", "", "", "-1");
                    }

                    //new BLL.ORDERDETAIL().AddDataRowToDataTable(this.DataTableOrderDetail, dstProduct.Tables[0].Rows[0]["spdm"].ToString(), Convert.ToDecimal(dstVipSet.Tables[0].Rows[0]["ZK"]), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["BZSJ"]), dstProduct.Tables[0].Rows[0]["spmc"].ToString(), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["CA_WEIGHT"]));
                }
                BindOrderDetail(this.DataTableOrderDetail);

                hidOrderDetailCount.Value = this.DataTableOrderDetail.Rows.Count.ToString();

                hidProduct.Value = "";
            }
            else if (Share.IsExistPromoteSales == "0")
            {
                string[] arrayProductCode = hidProduct.Value.Split(',');
                DataSet dstProduct;
                for (int i = 0; i < arrayProductCode.Length; i++)
                {
                    dstProduct = new BLL.SHANGPIN().GetProductInfoByCode(arrayProductCode[i]);
                    if (dstProduct.Tables[0].Rows.Count == 0)
                    {
                        continue;
                    }
                    new BLL.ORDERDETAIL().AddDataRowToDataTable(this.DataTableOrderDetail, dstProduct.Tables[0].Rows[0]["spdm"].ToString(), Convert.ToDecimal(dstVipSet.Tables[0].Rows[0]["ZK"]), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["BZSJ"]), dstProduct.Tables[0].Rows[0]["spmc"].ToString(), Convert.ToDecimal(dstProduct.Tables[0].Rows[0]["CA_WEIGHT"]), "0", "", "", "0");
                }
                BindOrderDetail(this.DataTableOrderDetail);
                hidOrderDetailCount.Value = this.DataTableOrderDetail.Rows.Count.ToString();
                hidProduct.Value = "";
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    private void FillValueIntoOrderDetailDataTable(DataTable tbl)
    {
        Label lblCode;
        Label lblName;
        DropDownList dropColor;
        DropDownList dropSize;
        TextBox txtQuantity;
        Label lblSprice;
        TextBox txtDiscount;
        //Label lblAprice;
        //Label lblSamt;
        //Label lblAamt;
        //Label lblWeight;
        HtmlInputHidden hidWeight;
        HtmlInputHidden hidIsPresent;
        HtmlInputHidden hidPresentSource;
        HtmlInputHidden hidPreferentialMode;
        HtmlInputHidden hidPromotionId;
        HtmlInputHidden hidSprice;
        HtmlInputHidden hidAprice;
        HtmlInputHidden hidPromotionOffAmt;
        HtmlInputHidden hidPromotionIsUseCustomerDiscount;

        for (int i = 0; i < dlistOrderDetail.Items.Count; i++)
        {
            lblCode = (Label)dlistOrderDetail.Items[i].FindControl("lblCode");
            lblName = (Label)dlistOrderDetail.Items[i].FindControl("lblName");
            dropColor = (DropDownList)dlistOrderDetail.Items[i].FindControl("dropColor");
            dropSize = (DropDownList)dlistOrderDetail.Items[i].FindControl("dropSize");
            txtQuantity = (TextBox)dlistOrderDetail.Items[i].FindControl("txtQuantity");
            lblSprice = (Label)dlistOrderDetail.Items[i].FindControl("lblSprice");
            hidSprice = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidSprice");
            hidAprice = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidAprice");
            txtDiscount = (TextBox)dlistOrderDetail.Items[i].FindControl("txtDiscount");
            //lblAprice = (Label)dlistOrderDetail.Items[i].FindControl("lblAprice");
            //lblSamt = (Label)dlistOrderDetail.Items[i].FindControl("lblSamt");
            //lblAamt = (Label)dlistOrderDetail.Items[i].FindControl("lblAamt");
            //lblWeight = (Label)dlistOrderDetail.Items[i].FindControl("lblWeight");
            hidWeight = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidWeight");
            hidIsPresent = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidIsPresent");
            hidPresentSource = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidPresentSource");
            hidPreferentialMode = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidPreferentialMode");
            hidPromotionId = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidPromotionId");
            hidPromotionOffAmt = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidPromotionOffAmt");
            hidPromotionIsUseCustomerDiscount = (HtmlInputHidden)dlistOrderDetail.Items[i].FindControl("hidPromotionIsUseCustomerDiscount");

            tbl.Rows[i]["od_detailid"] = Convert.ToString(i + 1);
            tbl.Rows[i]["od_colorcode"] = dropColor.SelectedValue;
            tbl.Rows[i]["od_sizecode"] = dropSize.SelectedValue;
            tbl.Rows[i]["od_cmdcode"] = lblCode.Text;
            tbl.Rows[i]["od_qty"] = Convert.ToInt32(txtQuantity.Text.Trim());
            tbl.Rows[i]["od_disc"] = Convert.ToDecimal(txtDiscount.Text.Trim());
            tbl.Rows[i]["od_sprice"] = Convert.ToDecimal(hidSprice.Value);
            tbl.Rows[i]["spmc"] = lblName.Text.Trim();
            tbl.Rows[i]["od_aprice"] = Convert.ToDecimal(hidAprice.Value);
            tbl.Rows[i]["od_samt"] = Convert.ToDecimal(hidSprice.Value) * Convert.ToInt32(txtQuantity.Text.Trim());
            tbl.Rows[i]["od_aamt"] = Convert.ToDecimal(hidAprice.Value) * Convert.ToInt32(txtQuantity.Text.Trim());
            tbl.Rows[i]["od_weight"] = Convert.ToDecimal(hidWeight.Value);

            tbl.Rows[i]["OD_FIELD2"] = hidIsPresent.Value;
            tbl.Rows[i]["OD_FIELD1"] = hidPresentSource.Value;
            tbl.Rows[i]["OD_OFFERNO"] = hidPreferentialMode.Value;
            tbl.Rows[i]["OD_OFFERID"] = hidPromotionId.Value;
            tbl.Rows[i]["PromotionOffAmt"] = Convert.ToDecimal(hidPromotionOffAmt.Value);
            tbl.Rows[i]["PromotionIsUseCustomerDiscount"] = Convert.ToInt32(hidPromotionIsUseCustomerDiscount.Value);
        }
    }

    public void RaiseCallbackEvent(string eventArgument)
    {
        if (Share.IsExistPromoteSales == "1")
        {
            SqlDataReader dataReader = BLL.Promotion.GetRLJE(Convert.ToDecimal(eventArgument));
            if (dataReader.HasRows)
            {
                if (dataReader.Read())
                {
                    result = dataReader["BYZD6"].ToString() + "|" + dataReader["DJBH"].ToString();
                    dataReader.Close();
                    dataReader.Dispose();
                }
            }
            else
            {
                result = "";
            }
        }
        else
        {
            result = "";
        }
    }
    public string GetCallbackResult()
    {
        return result;
    }

    protected void dilstOrderDetail_DDLCHANGE_Click(object sender, EventArgs e)
    {
        if (IsUseColorSize)
        {
            DropDownList dropColor = (DropDownList)sender;
            Label lblProductCode = (Label)dropColor.Parent.FindControl("lblCode");
            DropDownList dropSize = (DropDownList)dropColor.Parent.FindControl("dropSize");
            BindDropProductSize(dropSize, lblProductCode.Text, dropColor.SelectedValue);
        }
        else
        {
            return;
        }
    }

    #endregion

    #region 支付明细控件绑定及相关操作



    private void BindPayDetail()
    {
        this.DataTableOrderPayDetail = new BLL.PAYDETAIL().GetOrderPayDetailByOrderId(this.Code).Tables[0];
        dlistPayDocPayDetail.DataSource = this.DataTableOrderPayDetail;
        dlistPayDocPayDetail.DataBind();
    }

    private void BindPayDetail(DataTable dtbl)
    {
        dlistPayDocPayDetail.DataSource = dtbl;
        dlistPayDocPayDetail.DataBind();
    }

    protected void dlistPayDocPayDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            DropDownList dropDealType = (DropDownList)e.Item.FindControl("dropDealType");
            for (int i = 0; i < dropDealType.Items.Count; i++)
            {
                if (dropDealType.Items[i].Value == this.DataTableOrderPayDetail.Rows[e.Item.ItemIndex]["PD_DTCODE"].ToString())
                {
                    dropDealType.SelectedIndex = i;
                    break;
                }
            }


            DropDownList dropPayType = (DropDownList)e.Item.FindControl("dropPayType");
            if (dropPayType != null)
            {
                if (this.DataTableOrderPayDetail.Rows[e.Item.ItemIndex]["PD_DTCODE"].ToString() != "")
                {
                    BindDropPayType(this.DataTableOrderPayDetail.Rows[e.Item.ItemIndex]["PD_DTCODE"].ToString(), dropPayType);
                    for (int i = 0; i < dropPayType.Items.Count; i++)
                    {
                        if (dropPayType.Items[i].Value.Contains(this.DataTableOrderPayDetail.Rows[e.Item.ItemIndex]["PD_PAYTYPE"].ToString() + "|"))
                        {
                            dropPayType.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    BindDropPayType(dropDealType.Items[0].Value, dropPayType);
                }
            }
            //统计
            TextBox txtZFDetail = (TextBox)e.Item.FindControl("txtPayAmount");
            SumZF += decimal.Parse(txtZFDetail.Text);
        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {
            ((HtmlInputText)e.Item.FindControl("c5")).Value = SumZF.ToString();
        }
    }
    protected void dlistPayDocPayDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.ToLower() == "del")
            {
                FillValueIntoOrderPayDetailDataTable(this.DataTableOrderPayDetail);

                BindPayDetail(new BLL.PAYDOCPAYDETAIL().SubDataRowFromDataTable(this.DataTableOrderPayDetail, e.Item.ItemIndex));
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }

    }

    private void BindDropPayType(string dealType, DropDownList drop)
    {
        DataSet dst = new BLL.PAYTYPE_DEALTYPE().P_DealType_GetPayTypeByCode(dealType);
        ListItem tempItem;
        drop.Items.Clear();
        for (int i = 0; i < dst.Tables[0].Rows.Count; i++)
        {
            tempItem = new ListItem();
            tempItem.Text = dst.Tables[0].Rows[i]["PT_NAME"].ToString();
            tempItem.Value = dst.Tables[0].Rows[i]["PT_CODE"].ToString() + "|" + dst.Tables[0].Rows[i]["PT_HAVEDEAL"].ToString();
            drop.Items.Add(tempItem);
        }
        ListItem item = new ListItem();
        item.Value = "-1";
        item.Text = "";
        drop.Items.Insert(0, item);

    }

    private void FillValueIntoOrderPayDetailDataTable(DataTable tbl)
    {
        DropDownList dropDealType;
        DropDownList dropPayType;
        TextBox txtPayAmount;
        TextBox txtPayDate;
        TextBox txtDealID;
        TextBox txtDealDate;
        Label lblAccount;
        TextBox txtNotes;

        for (int i = 0; i < dlistPayDocPayDetail.Items.Count; i++)
        {
            dropDealType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropDealType");
            dropPayType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropPayType");
            txtPayAmount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayAmount");
            txtPayDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayDate");
            txtDealID = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealID");
            txtDealDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealDate");
            lblAccount = (Label)dlistPayDocPayDetail.Items[i].FindControl("lblAccount");
            txtNotes = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtNotes");

            if (dropPayType.SelectedIndex != 0)
            {
                string[] selectValue = dropPayType.SelectedItem.Value.Split('|');
                if (selectValue[1] == "1" && txtDealID.Text.Trim() == "")
                {
                    throw new Exception("您选择的支付方式必须输入交易号，请输入！");
                }
                tbl.Rows[i]["PD_DTCODE"] = dropDealType.SelectedValue;
                tbl.Rows[i]["PD_PAYTYPE"] = selectValue[0];
                tbl.Rows[i]["PD_PAYAMT"] = Convert.ToDecimal(txtPayAmount.Text.Trim());
                tbl.Rows[i]["PD_PAYDATE"] = txtPayDate.Text.Trim() == "" ? DateTime.Now : Convert.ToDateTime(txtPayDate.Text.Trim());
                tbl.Rows[i]["PD_DEALID"] = txtDealID.Text.Trim();
                tbl.Rows[i]["PD_DEALDATE"] = txtDealDate.Text.Trim() == "" ? DateTime.Now : Convert.ToDateTime(txtDealDate.Text.Trim());
                tbl.Rows[i]["PD_ACCOUNT"] = lblAccount.Text.Trim();
                tbl.Rows[i]["PD_NOTE"] = txtNotes.Text.Trim();
            }
            else
            {
                tbl.Rows[i]["PD_DTCODE"] = dropDealType.SelectedValue;
                tbl.Rows[i]["PD_PAYTYPE"] = "-1";
                tbl.Rows[i]["PD_PAYAMT"] = Convert.ToDecimal(txtPayAmount.Text.Trim());
                tbl.Rows[i]["PD_PAYDATE"] = txtPayDate.Text.Trim() == "" ? DateTime.Now : Convert.ToDateTime(txtPayDate.Text.Trim());
                tbl.Rows[i]["PD_DEALID"] = txtDealID.Text.Trim();
                tbl.Rows[i]["PD_DEALDATE"] = txtDealDate.Text.Trim() == "" ? DateTime.Now : Convert.ToDateTime(txtDealDate.Text.Trim());
                tbl.Rows[i]["PD_ACCOUNT"] = lblAccount.Text.Trim();
                tbl.Rows[i]["PD_NOTE"] = txtNotes.Text.Trim();
            }



        }

    }

    protected void btnAddPayDetail_Click(object sender, EventArgs e)
    {
        try
        {
            FillValueIntoOrderPayDetailDataTable(this.DataTableOrderPayDetail);

            this.DataTableOrderPayDetail = new BLL.PAYDETAIL().AddDataRowToDataTable(this.DataTableOrderPayDetail);

            BindPayDetail(this.DataTableOrderPayDetail);


        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void DataList2_DDLCHANGE_Click(object sender, EventArgs e)
    {
        DropDownList dropDealType = (DropDownList)sender;
        DropDownList dropPayType = (DropDownList)dropDealType.Parent.FindControl("dropPayType");
        Label lblAccount = (Label)dropDealType.Parent.FindControl("lblAccount");
        lblAccount.Text = "";
        BindDropPayType(dropDealType.SelectedValue, dropPayType);
    }

    protected void DataList2_DDLDROPCHANGE_Click(object sender, EventArgs e)
    {
        DropDownList dropPayType = (DropDownList)sender;
        Label lblAccount = (Label)dropPayType.Parent.FindControl("lblAccount");
        foreach (Model.PAYTYPE temp in this.PayType)
        {
            if (dropPayType.SelectedValue.Contains(temp.PT_CODE))
            {
                lblAccount.Text = temp.PA_ACCOUNT;
                break;
            }
        }

    }

    private void GetPayType()
    {
        this.PayType = new BLL.PAYTYPE().GetAllList();
    }

    #endregion

    #region 礼券支付控件绑定及相关操作



    private void BindDataListCoupon(string bindType)
    {
        DataSet dstUsableCouponOfCustomer;
        DataSet dstCouponUsedInThisOrder;
        switch (bindType)
        {
            case "payAfterReceive":
                dlistCoupon.DataSource = null;
                dlistCoupon.DataBind();
                break;
            case "lock":
                dstUsableCouponOfCustomer = new BLL.LIQUAN_CUSTOMER().GetUsableCouponByCustomerCode(hidCustomerId.Value, this.Code);

                dlistCoupon.DataSource = dstUsableCouponOfCustomer;
                dlistCoupon.DataBind();
                dlistCoupon.Enabled = false;
                break;
            case "notAudit":
                dstUsableCouponOfCustomer = new BLL.LIQUAN_CUSTOMER().GetUsableCouponByCustomerCode(hidCustomerId.Value, this.Code);

                dlistCoupon.DataSource = dstUsableCouponOfCustomer;
                dlistCoupon.DataBind();
                //dlistCoupon.Enabled = false;
                break;
            case "isAudit":
                dstCouponUsedInThisOrder = new BLL.PAYDETAIL().GetPayDetailsByOrderIdAndPayType(this.Code, "002");
                dlistCoupon.DataSource = dstCouponUsedInThisOrder;
                dlistCoupon.DataBind();
                dlistCoupon.Enabled = false;
                break;
            case "delete":
                dlistCoupon.DataSource = null;
                dlistCoupon.DataBind();
                break;
        }

    }

    #endregion

    #region 按钮操作
    #region 锁定
    protected void btnLock_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00008"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Model.ORDERDOC od = new BLL.ORDERDOC().GetModel(this.Code);
        if (od.ORDER_LOCK == 1)
        {
            Share.Alert(Page, "订单已被锁定"); return;
        }
        od.ORDER_LOCK = 1;
        od.ORDER_LOCKER = Share.UserValue(0);
        od.ORDER_LOCKDATE = DateTime.Now;
        if (new BLL.ORDERDOC().Update(od))
        {
            Share.InsertLog("400101", "00008");
            Response.Redirect("OrderDetail.aspx?code=" + this.Code);
        }
        else
        {
            Share.Alert(Page, "锁定失败"); return;
        }
    }
    #endregion

    #region 解锁
    protected void btnUnlock_Click(object sender, EventArgs e)
    {
        if (hidIsUnlock.Value == "0")
        {
            return;
        }
        if (!Check.CheckPermission("400101", "00009"))
        {
            Share.Alert(Page, "无权操作"); return;
        }
        Model.ORDERDOC od = new BLL.ORDERDOC().GetModel(this.Code);
        string user = Share.UserValue(0);
        //if (user != "admin")
        //{
        //    if (od.ORDER_LOCKER != user)
        //    {
        //        Share.Alert(Page, "无权解锁"); return;
        //    }
        //}

        od.ORDER_LOCK = 0;
        od.ORDER_LOCKER = "";
        od.ORDER_UPLOCKER = user;
        od.ORDER_UPLOCKDATE = DateTime.Now;
        if (new BLL.ORDERDOC().Update(od))
        {
            Share.InsertLog("400101", "00009");
            Response.Redirect("OrderDetail.aspx?code=" + this.Code);
        }
        else
        {
            Share.Alert(Page, "解锁失败"); return;
        }
    }
    #endregion

    #region 保存
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (!Check.CheckPermission("400101", "00017"))
            {
                Share.Alert(Page, "无权操作"); return;
            }
            if (dlistOrderDetail.Items.Count == 0)
            {
                Share.Alert(Page, "请选择要购买的商品!"); return;
            }
            Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
            if (order == null)
            {
                Share.Alert(Page, "系统无法读取到该订单!"); return;
            }
            if (order.ORDER_CHECK == 1)
            {
                Share.Alert(Page, "此订单已审核，不允许修改!"); return;
            }
            ValidShipAddressInfo();

            FillValueIntoOrderDetailDataTable(this.DataTableOrderDetail);
            FillValueIntoOrderPayDetailDataTable(this.DataTableOrderPayDetail);

            if (((DropDownList)dlistOrderMain.Items[0].FindControl("dropPayAfterReceive")).SelectedValue == "1")
            {
                if (this.DataTableOrderPayDetail.Rows.Count > 0)
                {
                    Share.Alert(Page, "货到付款订单不能有支付明细!"); return;
                }
            }

            decimal totalWeight = 0.00M;
            decimal productTotalPrice = 0.00M;
            int totalQuantity = 0;
            decimal totalPrice = 0.00M;
            decimal payAmount = 0.00M;

            for (int i = 0; i < this.DataTableOrderDetail.Rows.Count; i++)
            {
                totalWeight += Convert.ToDecimal(this.DataTableOrderDetail.Rows[i]["od_weight"]) * Convert.ToInt32(this.DataTableOrderDetail.Rows[i]["od_qty"]);
                productTotalPrice += Convert.ToDecimal(this.DataTableOrderDetail.Rows[i]["od_aamt"]);
                totalQuantity += Convert.ToInt32(this.DataTableOrderDetail.Rows[i]["od_qty"]);
            }

            totalPrice = productTotalPrice - Convert.ToDecimal(((TextBox)dlistOrderMain.Items[0].FindControl("txtOfferAmt")).Text.Trim()) + Convert.ToDecimal(((TextBox)dlistOrderMain.Items[0].FindControl("txtTranCost")).Text.Trim());

            bool isSecDeal = false;
            for (int i = 0; i < this.DataTableOrderPayDetail.Rows.Count; i++)
            {
                if (this.DataTableOrderPayDetail.Rows[i]["pd_dtcode"].ToString() == "002")
                {
                    isSecDeal = true;
                    //break;
                }
                payAmount += Convert.ToDecimal(this.DataTableOrderPayDetail.Rows[i]["pd_payamt"]);
            }

            bool isPromotion = false;
            if (hidOrderMainDJBH.Value == "")
            {
                for (int i = 0; i < this.DataTableOrderDetail.Rows.Count; i++)
                {
                    if (this.DataTableOrderDetail.Rows[i]["od_offerid"].ToString() != "")
                    {
                        isPromotion = true;
                        break;
                    }
                }
            }
            else
            {
                isPromotion = true;
            }


            StringBuilder strSql = new StringBuilder();
            strSql.Append("update OrderDoc set ORDER_OFFERAMT=");
            strSql.Append(((TextBox)dlistOrderMain.Items[0].FindControl("txtOfferAmt")).Text.Trim());
            strSql.Append(",ORDER_AMT=");
            strSql.Append(productTotalPrice);
            strSql.Append(",ORDER_TAMT=");
            strSql.Append(productTotalPrice + Convert.ToDecimal(((TextBox)dlistOrderMain.Items[0].FindControl("txtTranCost")).Text.Trim()));
            strSql.Append(",ORDER_PAYAMT=");
            strSql.Append(payAmount);
            strSql.Append(",ORDER_QTY=");
            strSql.Append(totalQuantity);
            strSql.Append(",ORDER_AAMT=");
            strSql.Append(totalPrice);
            strSql.Append(",ORDER_TRANCOST=");
            strSql.Append(((TextBox)dlistOrderMain.Items[0].FindControl("txtTranCost")).Text.Trim());
            strSql.Append(",ORDER_NOTE='");
            strSql.Append(((TextBox)dlistOrderMain.Items[0].FindControl("txtNote")).Text.Trim());
            strSql.Append("',ORDER_COSTNATURE='");
            strSql.Append(((DropDownList)dlistOrderMain.Items[0].FindControl("dropCostNature")).SelectedValue);
            strSql.Append("',ORDER_OFCODE='");
            strSql.Append(((DropDownList)dlistOrderMain.Items[0].FindControl("dropOrderSource")).SelectedValue);
            strSql.Append("',ORDER_APAY=");
            strSql.Append(((DropDownList)dlistOrderMain.Items[0].FindControl("dropPayAfterReceive")).SelectedValue);
            strSql.Append(",ORDER_WEIGHT=");
            strSql.Append(totalWeight);
            strSql.Append(",ORDER_SECDEAL=");
            strSql.Append(isSecDeal ? 1 : 0);
            strSql.Append(",ORDER_TRANERCODE='");
            strSql.Append(((DropDownList)dlistOrderMain.Items[0].FindControl("dropTraner")).SelectedValue);
            if (((CheckBox)dlistOrderMain.Items[0].FindControl("chkNINV")).Checked)
            {
                strSql.Append("',ORDER_NINV=1,ORDER_INVTITLE='");
                strSql.Append(((TextBox)dlistOrderMain.Items[0].FindControl("txtINVTITLE")).Text.Trim());
            }
            else
            {
                strSql.Append("',ORDER_NINV=0,ORDER_INVTITLE='");
            }

            strSql.Append("',ORDER_GETER='");
            strSql.Append(txtReceiver.Value);
            strSql.Append("',ORDER_GETADDRESS='");
            strSql.Append(txtAddress.Value.Replace(",", " "));
            strSql.Append("',ORDER_GETPOSTCODE='");
            strSql.Append(txtPostCode.Value);
            strSql.Append("',ORDER_GETERPHONE1='");
            strSql.Append(PhoneStr);
            strSql.Append("',ORDER_GETERPHONE2='");
            strSql.Append(txtMobile.Value);
            strSql.Append("',order_Province='");
            strSql.Append(Province.Items[Province.SelectedIndex].Value);
            strSql.Append("',order_city='");
            strSql.Append(hidCityCode.Value);
            strSql.Append("',order_area='");
            strSql.Append(hidAreaCode.Value);
            strSql.Append("',ORDER_OFFERID='");
            strSql.Append(hidOrderMainDJBH.Value);
            strSql.Append("',ORDER_IsPromotion=");
            strSql.Append(isPromotion ? 1 : 0);
            if (hidIsUseStationDelivery.Value == "1")
            {
                strSql.Append(",BYZD4=");
                strSql.Append(hidServiceStationId.Value);
                strSql.Append(",BYZD5='1',BYZD6='");
                strSql.Append(hidIsPayAfterReceive.Value);
                strSql.Append("',byzd7='0'");
            }
            else if (hidIsUseStationDelivery.Value == "0")
            {
                strSql.Append(",BYZD4=0,BYZD5='0',BYZD6='0',byzd7='0'");
            }
            strSql.Append(" where order_id='");
            strSql.Append(this.Code);
            strSql.Append("'|");

            decimal pointRate = new BLL.V_VIPSET().GetBaseBS(hidCustomerId.Value);
            if (pointRate == 0)
            {
                Share.Alert(Page, "系统无法获取到该会员的积分兑换比率!"); return;
            }

            strSql.Append("delete from ORDERDETAIL where OD_ID='");
            strSql.Append(this.Code);
            strSql.Append("'|");

            for (int i = 0; i < this.DataTableOrderDetail.Rows.Count; i++)
            {
                if (this.DataTableOrderDetail.Rows[i]["OD_DISC"].ToString() == "")//|| decimal.Parse(this.DataTableOrderDetail.Rows[i]["OD_DISC"].ToString()) == 0.00M
                { throw new Exception("折扣不能为零或为空"); }
                if (this.DataTableOrderDetail.Rows[i]["OD_COLORCODE"] == "-1")
                {
                    Share.Alert(Page, "请选择颜色!"); return;
                }
                if (this.DataTableOrderDetail.Rows[i]["OD_SIZECODE"] == "-1")
                {
                    Share.Alert(Page, "请选择尺码!"); return;
                }
                strSql.Append("INSERT INTO ORDERDETAIL([OD_ID],[OD_DETAILID],[OD_CMDCODE],[OD_COLORCODE],[OD_SIZECODE],");
                strSql.Append("[OD_QTY],[OD_SPRICE],[OD_DISC],[OD_APRICE],[OD_SAMT],[OD_AAMT],[OD_ADDITG],[OD_WEIGHT],");
                strSql.Append("[OD_FIELD1],[OD_FIELD2],[OD_OFFERNO],[OD_OFFERID])VALUES('");
                strSql.Append(this.Code);
                strSql.Append("','");
                strSql.Append(i + 1);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_CMDCODE"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_COLORCODE"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_SIZECODE"]);
                strSql.Append("',");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_QTY"]);
                strSql.Append(",");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_SPRICE"]);
                strSql.Append(",");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_DISC"]);
                strSql.Append(",");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_APRICE"]);
                strSql.Append(",");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_SAMT"]);
                strSql.Append(",");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_AAMT"]);
                strSql.Append(",");
                strSql.Append(Convert.ToDecimal(this.DataTableOrderDetail.Rows[i]["OD_AAMT"]) * pointRate);
                strSql.Append(",");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_WEIGHT"]);
                strSql.Append(",'");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_FIELD1"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_FIELD2"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_OFFERNO"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_OFFERID"]);
                strSql.Append("')| ");
            }

            strSql.Append("delete from paydetail where pd_Id='");
            strSql.Append(this.Code);
            strSql.Append("'|");

            int count = 0;
            for (int i = 0; i < this.DataTableOrderPayDetail.Rows.Count; i++)
            {
                strSql.Append("Insert into PayDetail([pd_id],[pd_detailid],[pd_paytype],[pd_payamt],[pd_paydate],[pd_dealid],[pd_dealdate],[pd_account],[pd_note],[pd_dtcode])values('");
                strSql.Append(this.Code);
                strSql.Append("','");
                strSql.Append(i + 1);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_paytype"]);
                strSql.Append("',");
                strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_payamt"]);
                strSql.Append(",'");
                strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_paydate"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_dealid"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_dealdate"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_account"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_note"]);
                strSql.Append("','");
                strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_dtcode"]);
                strSql.Append("')|");

                count++;
            }

            for (int i = 0; i < dlistCoupon.Items.Count; i++)
            {
                strSql.Append("update LIQUAN_CUSTOMER set frozen=0 where CouponCode='");
                strSql.Append(((Label)dlistCoupon.Items[i].FindControl("lblCouponCode")).Text);
                strSql.Append("' and CustomerCode='");
                strSql.Append(order.ORDER_CUSTOMERCODE);
                strSql.Append("'|");
                if (((CheckBox)dlistCoupon.Items[i].FindControl("chkCoupon")).Checked)
                {
                    strSql.Append("Insert into PayDetail([pd_id],[pd_detailid],[pd_paytype],[pd_payamt],[pd_paydate],[pd_dealid],[pd_dealdate],[pd_account],[pd_note],[pd_dtcode])values('");
                    strSql.Append(this.Code);
                    strSql.Append("','");
                    strSql.Append(++count);
                    strSql.Append("','002',");
                    strSql.Append(((Label)dlistCoupon.Items[i].FindControl("lblCouponAmount")).Text);
                    strSql.Append(",'");
                    strSql.Append(DateTime.Now);
                    strSql.Append("','");
                    strSql.Append(((Label)dlistCoupon.Items[i].FindControl("lblCouponCode")).Text);
                    strSql.Append("','");
                    strSql.Append(DateTime.Now);
                    strSql.Append("','");
                    strSql.Append(order.ORDER_CUSTOMERCODE);
                    strSql.Append("','','001')|");

                    strSql.Append("update LIQUAN_CUSTOMER set frozen=1 where CouponCode='");
                    strSql.Append(((Label)dlistCoupon.Items[i].FindControl("lblCouponCode")).Text);
                    strSql.Append("' and CustomerCode='");
                    strSql.Append(order.ORDER_CUSTOMERCODE);
                    strSql.Append("'|");
                }
            }
            string stringSql = strSql.ToString();
            char[] charToTrim = new char[] { '|' };
            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
            if (new SQLServerDAL.ORDERDETAIL().UpdateOrderDetailAndOrderMain(sqlCommandArray))
            {
                Share.InsertLog("400101", "00017");
                Response.Redirect("OrderDetail.aspx?code=" + this.Code);
            }
            else
            {
                Share.Alert(Page, "保存失败!"); return;
            }
        }
        catch (Exception ex)
        {
            Share.Alert(Page, ex.Message); return;
        }
    }
    #endregion

    #region 客服审核
    protected void btnAudit_Click(object sender, EventArgs e)
    {
        try
        {
            if (hidIsNeedToSave.Value == "1")
            {
                if (!Save())
                {
                    throw new Exception("保存失败");
                }
            }
            if (!Check.CheckPermission("400101", "00010"))
            {
                Share.Alert(Page, "无权操作"); return;
            }

            Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
            if (order == null)
            {
                Share.Alert(Page, "系统无法获取订单信息!"); return;
            }
            if (order.ORDER_LOCK != 1)
            {
                Share.Alert(Page, "订单未锁定,不能审核!"); return;
            }
            if (order.ORDER_CHECK == 1)
            {
                Share.Alert(Page, "此订单已审核!"); return;
            }
            if (order.ORDER_LOCKER != Share.UserValue(0))
            {
                Share.Alert(Page, "由于您不是本订单的锁定人，所以无权审核!"); return;
            }

            new BLL.TRANERCOST().GetTranCost(order.ORDER_TRANERCODE, order.ORDER_CITY, order.ORDER_WEIGHT);

            CheckBox chkNINV = (CheckBox)dlistOrderMain.Items[0].FindControl("chkNINV");
            TextBox txtINVTITLE = (TextBox)dlistOrderMain.Items[0].FindControl("txtINVTITLE");
            if (chkNINV.Checked)
            {
                if (txtINVTITLE.Text.Trim() == "")
                {
                    Share.Alert(Page, "如果需要发票,请填写发票抬头!"); return;
                }
            }

            ValidShipAddressInfo(order.ORDER_GETER, order.ORDER_GETADDRESS, order.ORDER_GETERPHONE1, order.ORDER_GETPOSTCODE, order.ORDER_GETERPHONE2);

            bool isEnoughStock = true;
            bool isNoStock = true;
            //校验可用库存

            string productCode;
            string colorCode;
            string sizeCode;
            decimal quantity;
            string productName = "";
            string restockProductName = "";
            string noStockProductName = "";
            string noColorSizeRestoreSet = "";//没有颜色尺码级的可补货设置

            string noRestoreSet = "";//没有商品级的可补货设置

            
            StringBuilder sbOrderId = new StringBuilder();//支付明细中具有相同支付方式和交易号的订单
            Model.COMMODITY_AUTO product;

            for (int g = 0; g < this.DataTableOrderDetail.Rows.Count; g++)
            {
                productCode = this.DataTableOrderDetail.Rows[g]["od_cmdcode"].ToString();
                colorCode = this.DataTableOrderDetail.Rows[g]["od_colorcode"].ToString();
                sizeCode = this.DataTableOrderDetail.Rows[g]["od_sizecode"].ToString();
                quantity = Convert.ToDecimal(this.DataTableOrderDetail.Rows[g]["od_qty"]);
                product = new BLL.COMMODITY_AUTO().GetModel(productCode);
       
                DataTable dt = new BLL.SPKCB().OC_Product_StockListBywhere(1, 10, "SPKCB.SPDM", "spkcb.CKDM='" + ConfigurationManager.AppSettings["ckdm"].ToString() + "' and spkcb.KWDM='" + ConfigurationManager.AppSettings["kwdm"].ToString() + "' and spkcb.spdm='" + productCode + "' and gg1dm='" + colorCode + "' and gg2dm='" + sizeCode + "' ", 1, "");
                if (dt.Rows.Count == 0)
                {
                    Share.Alert(Page, "商品 " + product.CA_CODE + " " + product.CA_NAME + " " + new BLL.GUIGE1().GetMC(colorCode) + " " + new BLL.GUIGE2().GetMC(sizeCode) +" 尚未配货到网店仓库，不能审核！"); return;
                }
                string spzs = new BLL.SPKCB().OC_Product_KEYONG_Stocks("spkcb.CKDM='" + ConfigurationManager.AppSettings["ckdm"].ToString() + "' and spkcb.KWDM='" + ConfigurationManager.AppSettings["kwdm"].ToString() + "' and spkcb.spdm='" + productCode + "' and gg1dm='" + colorCode + "' and gg2dm='" + sizeCode + "' ");
                if (Decimal.Parse(spzs) < 0)
                {
                    DataSet dstRestock;
                    if (IsRestockUseColorSize)
                    {
                        dstRestock = new BLL.RingNor.ShangPinBL().GetSPRestockModal(productCode, colorCode, sizeCode);
                    }
                    else
                    {
                        dstRestock = new BLL.RingNor.ShangPinBL().GetSPRestockModalByProductId(productCode);
                    }
                    if (dstRestock.Tables[0].Rows.Count > 0)
                    {
                        if (dstRestock.Tables[0].Rows[0]["ISRESTOCK"].ToString() == "1")
                        {
                            product = new BLL.COMMODITY_AUTO().GetModel(productCode);
                            if (product != null)
                            {
                                restockProductName += product.CA_CODE + " " + product.CA_NAME + " " + new BLL.GUIGE1().GetMC(colorCode) + " " + new BLL.GUIGE2().GetMC(sizeCode) + ",";
                            }
                        }
                        else if (dstRestock.Tables[0].Rows[0]["ISRESTOCK"].ToString() == "0")
                        {
                            isNoStock = false;
                            product = new BLL.COMMODITY_AUTO().GetModel(productCode);
                            if (product != null)
                            {
                                noStockProductName += product.CA_CODE + " " + product.CA_NAME + " " + new BLL.GUIGE1().GetMC(colorCode) + " " + new BLL.GUIGE2().GetMC(sizeCode) + ",";
                            }
                        }
                    }
                    else
                    {
                        product = new BLL.COMMODITY_AUTO().GetModel(productCode);
                        if (IsRestockUseColorSize)
                        {
                            noColorSizeRestoreSet += product.CA_NAME + "(" + new BLL.GUIGE1().GetMC(colorCode) + "," + new BLL.GUIGE2().GetMC(sizeCode) + "),";
                            //Share.Alert(this.Page, "系统无法获取商品" + product.CA_NAME + "(" + new BLL.GUIGE1().GetMC(colorCode) + "," + new BLL.GUIGE2().GetMC(sizeCode) + ")" + "的可补货设置信息,请检查商品的可补货设置!"); return;
                        }
                        else
                        {
                            noRestoreSet += product.CA_NAME + ",";
                            //Share.Alert(this.Page, "系统无法获取商品" + product.CA_NAME + "的可补货设置信息,请检查商品的可补货设置!"); return;
                        }
                    }

                }
                if (quantity > Decimal.Parse(spzs))
                {
                    isEnoughStock = false;
                    product = new BLL.COMMODITY_AUTO().GetModel(productCode);
                    if (product != null)
                    {
                        productName += product.CA_CODE + " " + product.CA_NAME + " " + new BLL.GUIGE1().GetMC(colorCode) + " " + new BLL.GUIGE2().GetMC(sizeCode) + " <br />";
                        //break;
                    }
                }
            }
            if (noColorSizeRestoreSet.Length > 0)
            {
                Share.Alert(this.Page, "系统无法获取商品:" + noColorSizeRestoreSet.Substring(0,noColorSizeRestoreSet.Length-1) + "的可补货设置信息,请检查商品的可补货设置!"); return;
            }
            if (noRestoreSet.Length > 0)
            {
                Share.Alert(this.Page, "系统无法获取商品:" + noRestoreSet.Substring(0, noRestoreSet.Length-1) + "的可补货设置信息,请检查商品的可补货设置!"); return;
            }
            if (!isNoStock)
            {
                char[] charArray = new char[] { ',' };
                if (restockProductName != "")
                {
                    restockProductName = "无库存可补货商品：" + restockProductName + ",";
                }
                if (noStockProductName != "")
                {
                    noStockProductName = "无库存并且不可补货商品：" + noStockProductName + ",由于存在无库存并且不可补货商品，该订单不能审核。";
                }

                Share.Alert(Page, restockProductName + noStockProductName); return;
            }

            if (!isEnoughStock)
            {
                char[] charArray = new char[] { ',' };
                //lblProducts.Text = productName.TrimEnd(charArray);
                Products.InnerHtml = productName.TrimEnd(charArray);
                this.programmaticModalPopup.Show(); return;
            }

            if (order.ORDER_APAY == 0)
            {
                decimal payAmount = 0.00M;
                decimal accountPayAmount = 0.00M;
                decimal couponPayAmount = 0.00M;
                for (int i = 0; i < this.DataTableOrderPayDetail.Rows.Count; i++)
                {
                    payAmount += Convert.ToDecimal(this.DataTableOrderPayDetail.Rows[i]["pd_payamt"]);
                    if (this.DataTableOrderPayDetail.Rows[i]["pd_dtcode"].ToString() == "003")
                    {
                        accountPayAmount += Convert.ToDecimal(this.DataTableOrderPayDetail.Rows[i]["pd_payamt"]);
                    }

                    if (new BLL.PAYTYPE().GetModel(this.DataTableOrderPayDetail.Rows[i]["pd_paytype"].ToString()).PT_HAVEDEAL == 1)
                    {
                        if (this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString() == "")
                        {
                            Share.Alert(Page, "请输入交易号！"); return;
                        }
                        //检查支付明细中的交易号
                        DataSet dst = new BLL.PAYDETAIL().GetPayDetailByPayTypeAndDealId(this.DataTableOrderPayDetail.Rows[i]["pd_paytype"].ToString(), this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString());
                        //检查充值单中的交易号

                        string remittanceId = "";//和订单支付明细具有相同支付方式和交易号的充值单
                        new BLL.REMITTANCE().CheckRepeat(this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString(), out remittanceId, this.DataTableOrderPayDetail.Rows[i]["pd_paytype"].ToString());
                        
                        if (dst.Tables[0].Rows.Count > 1&&remittanceId.Length>0)
                        {
                            sbOrderId.Append("相同交易号："+this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString()); 
                            sbOrderId.Append(" 在订单：");
                            for (int j = 0; j < dst.Tables[0].Rows.Count; j++)
                            {
                                sbOrderId.Append(dst.Tables[0].Rows[j]["PD_ID"].ToString() + " ");//订单号

                            }
                            sbOrderId.Append(" 在充值单：");
                            sbOrderId.Append(remittanceId);
                            sbOrderId.Append("中存在.");
                        }
                        else if (dst.Tables[0].Rows.Count > 1 && remittanceId.Length == 0)
                        {
                            sbOrderId.Append("相同交易号：" + this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString());
                            sbOrderId.Append(" 在订单：");
                            for (int j = 0; j < dst.Tables[0].Rows.Count; j++)
                            {
                                sbOrderId.Append(dst.Tables[0].Rows[j]["PD_ID"].ToString() + " ");//订单号

                            }
                            sbOrderId.Append("中存在.");
                        }
                        else if (dst.Tables[0].Rows.Count ==1 && remittanceId.Length >0)
                        {
                            sbOrderId.Append("相同交易号："+this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString()); 
                            sbOrderId.Append(" 在充值单：");
                            sbOrderId.Append(remittanceId);
                            sbOrderId.Append("中存在.");
                        }
   

                    }
                }
                if (sbOrderId.Length > 0)
                {
                    Share.Alert(Page, sbOrderId.ToString()); return;
                }
                DataSet dstPayDetailCoupon = new BLL.PAYDETAIL().GetPayDetailsByOrderIdAndPayType(this.Code, "002");
                for (int i = 0; i < dstPayDetailCoupon.Tables[0].Rows.Count; i++)
                {
                    couponPayAmount += Convert.ToDecimal(dstPayDetailCoupon.Tables[0].Rows[i]["XFJE"]);
                }

                if (order.ORDER_AAMT > payAmount + couponPayAmount)
                {
                    Share.Alert(Page, "支付金额不足！"); return;
                }
                /*
                if (accountPayAmount > 0.00M)
                {
                    Model.V_VIPSET vvs = new BLL.V_VIPSET().GetModelByGKDM(order.ORDER_CUSTOMERCODE);
                    Model.V_VIP_ACCOUNT vva = new BLL.V_VIP_ACCOUNT().GetModel(vvs.DM);
                    if (vva == null)
                    {
                        if (0.00M + vvs.BYZD12 < accountPayAmount)
                        {
                            Share.Alert(Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                        }
                    }
                    else
                    {
                        if (vva.DQJE_1 + vvs.BYZD12 < accountPayAmount)
                        {
                            Share.Alert(Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                        }
                    }
                }*/
            }
            if (new BLL.ORDERDOC().P_Order_Audit(0, ConfigurationManager.AppSettings["ckdm"].ToString(), ConfigurationManager.AppSettings["kwdm"].ToString(), this.Code, Share.UserValue(0)))
            {
                Share.InsertLog("400101", "00010");
                if (order.ORDER_APAY == 1)
                {
                    FinancialAffairsAudit();
                }
                Response.Redirect("OrderDetail.aspx?code=" + this.Code);
            }
            else
            {
                Share.Alert(Page, "审批失败"); return;
            }
        }
        catch (Exception ex)
        {
            if (ex.Message == "系统无法查询到选定物流公司在选定地区的收费标准！")
            {
                return;
            }
            else
            {
                Share.Alert(Page, ex.Message);
            }
        }
    }
    #endregion

    #region 客服反审核



    protected void btnAntiAudit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00011"))
        {
            Share.Alert(Page, "无权操作"); return;
        }
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
        //if (order.ORDER_LOCK != 1)
        //{
        //    Share.Alert(Page, "订单未锁定,不能操作"); return;
        //}
        //if (order.ORDER_LOCKER != Share.UserValue(0))
        //{
        //    Share.Alert(Page, "由于您不是本订单的锁定人，所以无权操作!"); return;
        //}
        if (order.ORDER_CHECK != 1)
        {
            Share.Alert(Page, "此订单未客服审核,不能执行客服反审操作"); return;
        }
        if (order.ORDER_ACHECK == 1)
        {
            Share.Alert(Page, "此订单已经财务审核,不能执行客服反审操作"); return;
        }
        if (new BLL.ORDERDOC().P_Order_Audit(1, ConfigurationManager.AppSettings["ckdm"].ToString(), ConfigurationManager.AppSettings["kwdm"].ToString(), Request.QueryString["code"].ToString().Trim(), Share.UserValue(0)))
        {
            Share.InsertLog("400101", "00011");
            Response.Redirect("OrderDetail.aspx?code=" + this.Code);
        }
        else
        {
            Share.Alert(Page, "反审批失败"); return;
        }
    }
    #endregion

    #region 财务审核
    protected void btnFinancialAffairsAudit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00012"))
        {
            Share.Alert(Page, "无权操作"); return;
        }

        bool result = false;

        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(Request.QueryString["code"].ToString().Trim());//获取订单主表
        //if (order.ORDER_LOCK != 1)
        //{
        //    Share.Alert(Page, "订单未锁定,不能操作"); return;
        //}
        //if (order.ORDER_LOCKER != Share.UserValue(0))
        //{
        //    Share.Alert(Page, "由于您不是本订单的锁定人，所以无权操作!"); return;
        //}
        if (order.ORDER_CHECK != 1)
        {
            Share.Alert(Page, "订单未客服审核,不能执行财务审核"); return;
        }
        if (order.ORDER_ACHECK == 1)
        {
            Share.Alert(Page, "订单已经财务审核,不能重复操作"); return;
        }
        switch (order.ORDER_APAY.ToString())
        {
            case "0"://非货到付款




                DataSet ds = new BLL.PAYDETAIL().P_Order_GetProductZFMX(this.Code);//获取订单支付明细
                decimal payAmount = 0.00M;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    payAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["pd_payamt"]);
                }
                if (order.ORDER_AAMT <= payAmount)
                {


                    #region 含担保交易




                    if (order.ORDER_SECDEAL == 1)
                    {
                        decimal immediatePayAmount = 0.00M;
                        decimal accountPayAmount = 0.00M;
                        decimal couponPayAmount = 0.00M;
                        StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                        StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001" && ds.Tables[0].Rows[i]["PD_PAYTYPE"].ToString() != "002")
                            {
                                immediatePayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001" && ds.Tables[0].Rows[i]["PD_PAYTYPE"].ToString() == "002")
                            {
                                couponPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);

                                strSqlToUpdateBStyleDB.Append("update czkzcdmx set state = 5 where CZKBH='");
                                strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSqlToUpdateBStyleDB.Append("'|");

                                strSqlToUpdateErpDB.Append("update czkzcdmx set state = 5 where CZKBH='");
                                strSqlToUpdateErpDB.Append(ds.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSqlToUpdateErpDB.Append("'|");

                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "003")
                            {
                                accountPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else
                            {
                                continue;
                            }
                            strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=1,PD_GETAMT=");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            strSqlToUpdateBStyleDB.Append(",PD_GETDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("' where PD_ID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_ID"]);
                            strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        string operatorId = Share.UserValue(0);

                        //if (order.ORDER_PAYAMT <= immediatePayAmount + accountPayAmount)
                        //{
                        //    strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                        //    strSqlToUpdateBStyleDB.Append(operatorId);
                        //    strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                        //    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        //    strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                        //    strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                        //    strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                        //    strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                        //    strSqlToUpdateBStyleDB.Append("'|");
                        //}
                        //else
                        //{


                        if (couponPayAmount > 0)
                        {
                            strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                            strSqlToUpdateBStyleDB.Append(operatorId);
                            strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("',ORDER_CLEARAMT=ORDER_CLEARAMT+");
                            strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount + couponPayAmount);
                            strSqlToUpdateBStyleDB.Append(",Coupon=1,CouponMoney=");
                            strSqlToUpdateBStyleDB.Append(couponPayAmount);
                            strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                            strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                            strSqlToUpdateBStyleDB.Append("'|");
                        }
                        else if (couponPayAmount == 0)
                        {
                            strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                            strSqlToUpdateBStyleDB.Append(operatorId);
                            strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("',ORDER_CLEARAMT=ORDER_CLEARAMT+");
                            strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount + couponPayAmount);
                            strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                            strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                            strSqlToUpdateBStyleDB.Append("'|");
                        }
                        //}

                        Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                        if (userInfo == null)
                        {
                            Share.Alert(Page, "系统内无此会员信息！"); return;
                        }
                        Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                        if (userAccount == null)
                        {
                            strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateBStyleDB.Append(userInfo.DM);
                            strSqlToUpdateBStyleDB.Append("',0)|");

                            strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateErpDB.Append(userInfo.DM);
                            strSqlToUpdateErpDB.Append("',0)|");
                        }
                        if (accountPayAmount != 0)
                        {
                            if (accountPayAmount > userInfo.BYZD12 + userAccount.DQJE_1)
                            {
                                Share.Alert(this.Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                            }


                            string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount * -1, userInfo.DM);
                            strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                            string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("003", order.ORDER_ID, operatorId, operatorId, order.ORDER_CUSTOMERCODE, accountPayAmount * -1);
                            strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);

                        }

                        if (strSqlToUpdateErpDB.ToString() == "")
                        {
                            string stringSql = strSqlToUpdateBStyleDB.ToString();
                            char[] charToTrim = new char[] { '|' };
                            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                            result = new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
                        }
                        else
                        {
                            string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                            string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                            char[] charToTrim = new char[] { '|' };
                            string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                            string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                            result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                        }
                    }
                    #endregion
                    #region 不含担保交易
                    else
                    {
                        decimal immediatePayAmount = 0.00M;
                        decimal accountPayAmount = 0.00M;
                        decimal couponPayAmount = 0.00M;
                        StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                        StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001" && ds.Tables[0].Rows[i]["PD_PAYTYPE"].ToString() != "002")
                            {
                                immediatePayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001" && ds.Tables[0].Rows[i]["PD_PAYTYPE"].ToString() == "002")
                            {
                                couponPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);

                                strSqlToUpdateBStyleDB.Append("update czkzcdmx set state = 5 where CZKBH='");
                                strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSqlToUpdateBStyleDB.Append("'|");

                                strSqlToUpdateErpDB.Append("update czkzcdmx set state = 5 where CZKBH='");
                                strSqlToUpdateErpDB.Append(ds.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSqlToUpdateErpDB.Append("'|");

                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "003")
                            {
                                accountPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else
                            {
                                continue;
                            }
                            //strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=1,PD_GETAMT=");
                            //strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            //strSqlToUpdateBStyleDB.Append(" where PD_ID='");
                            //strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_ID"]);
                            //strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                            //strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                            //strSqlToUpdateBStyleDB.Append("'|");

                            strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=1,PD_GETAMT=");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            strSqlToUpdateBStyleDB.Append(",PD_GETDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("' where PD_ID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_ID"]);
                            strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        string operatorId = Share.UserValue(0);

                        if (order.ORDER_PAYAMT <= immediatePayAmount + accountPayAmount + couponPayAmount)
                        {
                            if (couponPayAmount > 0)
                            {
                                strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                                strSqlToUpdateBStyleDB.Append(operatorId);
                                strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                                strSqlToUpdateBStyleDB.Append(DateTime.Now);
                                strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                                strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount + couponPayAmount);
                                strSqlToUpdateBStyleDB.Append(",BYZD9='");
                                strSqlToUpdateBStyleDB.Append(DateTime.Now);
                                strSqlToUpdateBStyleDB.Append("',Coupon=1,CouponMoney=");
                                strSqlToUpdateBStyleDB.Append(couponPayAmount);
                                strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                                strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                                strSqlToUpdateBStyleDB.Append("'|");

                                BLL.Promotion.BuildInitCouponSqlString(immediatePayAmount + accountPayAmount, this.Code, order.ORDER_CUSTOMERCODE, strSqlToUpdateBStyleDB, strSqlToUpdateErpDB);
                            }
                            else if (couponPayAmount == 0)
                            {
                                strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                                strSqlToUpdateBStyleDB.Append(operatorId);
                                strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                                strSqlToUpdateBStyleDB.Append(DateTime.Now);
                                strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                                strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount + couponPayAmount);
                                strSqlToUpdateBStyleDB.Append(",BYZD9='");
                                strSqlToUpdateBStyleDB.Append(DateTime.Now);
                                strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                                strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                                strSqlToUpdateBStyleDB.Append("'|");

                                BLL.Promotion.BuildInitCouponSqlString(order.ORDER_AAMT, this.Code, order.ORDER_CUSTOMERCODE, strSqlToUpdateBStyleDB, strSqlToUpdateErpDB);
                            }
                        }
                        else
                        {
                            strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                            strSqlToUpdateBStyleDB.Append(operatorId);
                            strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("',ORDER_CLEARAMT=ORDER_CLEARAMT+");
                            strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount + couponPayAmount);
                            strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                            strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                        if (userInfo == null)
                        {
                            Share.Alert(Page, "系统内无此会员信息！"); return;
                        }
                        Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                        if (userAccount == null)
                        {
                            strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateBStyleDB.Append(userInfo.DM);
                            strSqlToUpdateBStyleDB.Append("',0)|");

                            strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateErpDB.Append(userInfo.DM);
                            strSqlToUpdateErpDB.Append("',0)|");
                        }
                        if (accountPayAmount != 0)
                        {
                            if (accountPayAmount > userInfo.BYZD12 + userAccount.DQJE_1)
                            {
                                Share.Alert(this.Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                            }


                            string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount * -1, userInfo.DM);
                            strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                            string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("003", order.ORDER_ID, operatorId, operatorId, order.ORDER_CUSTOMERCODE, accountPayAmount * -1);
                            strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);

                        }

                        if (strSqlToUpdateErpDB.ToString() == "")
                        {
                            string stringSql = strSqlToUpdateBStyleDB.ToString();
                            char[] charToTrim = new char[] { '|' };
                            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                            result = new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
                        }
                        else
                        {
                            string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                            string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                            char[] charToTrim = new char[] { '|' };
                            string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                            string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                            result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                        }
                    }
                    #endregion
                }
                else
                {
                    Share.Alert(Page, "支付金额不足"); return;
                }
                break;

            case "1":
                order.ORDER_ACHECK = 1;
                order.ORDER_ACHECKER = Share.UserValue(0);
                order.ORDER_ACHECKDATE = DateTime.Now;

                result = new BLL.ORDERDOC().Update(order);
                break;
        }
        if (result)
        {
            Share.InsertLog("400101", "00012");
            Response.Redirect("OrderDetail.aspx?code=" + this.Code);
        }
        else
        {
            Share.Alert(Page, "财务审核失败"); return;
        }
    }
    #endregion

    #region 财务反审核



    protected void btnFinancialAffairsAntiAudit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00013"))
        {
            Share.Alert(Page, "无权操作"); return;
        }

        bool result = false;

        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(Request.QueryString["code"].ToString().Trim());//获取订单主表
        //if (order.ORDER_LOCK != 1)
        //{
        //    Share.Alert(Page, "订单未锁定,不能操作"); return;
        //}
        //if (order.ORDER_LOCKER != Share.UserValue(0))
        //{
        //    Share.Alert(Page, "由于您不是本订单的锁定人，所以无权操作!"); return;
        //}
        if (order.ORDER_ACHECK != 1)
        {
            Share.Alert(Page, "订单未财务审核，不能执行反审操作!"); return;
        }
        if (order.ORDER_SEND == 1)
        {
            Share.Alert(Page, "订单已发货，不能执行反审操作!"); return;
        }
        switch (order.ORDER_APAY.ToString())
        {
            case "0"://即时到帐--2结算单审批修改结余款、3订单财务审批
                DataSet ds = new BLL.PAYDETAIL().P_Order_GetProductZFMX(this.Code);//获取订单支付明细
                decimal payAmount = 0.00M;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    payAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["pd_payamt"]);
                }
                if (order.ORDER_AAMT <= payAmount)
                {


                    #region 含担保交易




                    if (order.ORDER_SECDEAL == 1)
                    {
                        decimal immediatePayAmount = 0.00M;
                        decimal accountPayAmount = 0.00M;
                        decimal couponPayAmount = 0.00M;
                        StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                        StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001" && ds.Tables[0].Rows[i]["PD_PAYTYPE"].ToString() != "002")
                            {
                                immediatePayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001" && ds.Tables[0].Rows[i]["PD_PAYTYPE"].ToString() == "002")
                            {
                                couponPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);

                                strSqlToUpdateBStyleDB.Append("update czkzcdmx set state = 3 where CZKBH='");
                                strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSqlToUpdateBStyleDB.Append("'|");

                                strSqlToUpdateErpDB.Append("update czkzcdmx set state = 3 where CZKBH='");
                                strSqlToUpdateErpDB.Append(ds.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSqlToUpdateErpDB.Append("'|");

                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "003")
                            {
                                accountPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else
                            {
                                continue;
                            }
                            strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=0,PD_GETAMT=0 where PD_ID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_ID"]);
                            strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        string operatorId = Share.UserValue(0);


                        strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=0,ORDER_ACHECKER='',ORDER_ACHECKDATE=NULL");
                        strSqlToUpdateBStyleDB.Append(",ORDER_CLEAR=0,ORDER_CLEARAMT=ORDER_CLEARAMT-");
                        strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount + couponPayAmount);
                        strSqlToUpdateBStyleDB.Append(",BYZD9=NULL,Coupon=0,CouponMoney=0");
                        strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                        strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                        strSqlToUpdateBStyleDB.Append("'|");



                        Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                        if (userInfo == null)
                        {
                            Share.Alert(Page, "系统内无此会员信息！"); return;
                        }
                        Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                        if (userAccount == null)
                        {
                            Share.Alert(this.Page, "系统内无此会员的结余款信息，因此不能使用结余款支付！"); return;
                        }
                        if (accountPayAmount != 0)
                        {
                            //if (accountPayAmount > userInfo.BYZD12 + userAccount.DQJE_1)
                            //{
                            //    Share.Alert(this.Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                            //}


                            string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount, userInfo.DM);
                            strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                            string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("004", order.ORDER_ID, operatorId, operatorId, order.ORDER_CUSTOMERCODE, accountPayAmount);
                            strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);

                        }

                        if (strSqlToUpdateErpDB.ToString() == "")
                        {
                            string stringSql = strSqlToUpdateBStyleDB.ToString();
                            char[] charToTrim = new char[] { '|' };
                            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                            result = new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
                        }
                        else
                        {
                            string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                            string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                            char[] charToTrim = new char[] { '|' };
                            string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                            string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                            result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                        }
                    }
                    #endregion
                    #region 不含担保交易
                    else
                    {
                        decimal immediatePayAmount = 0.00M;
                        decimal accountPayAmount = 0.00M;
                        decimal couponPayAmount = 0.00M;
                        StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                        StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001" && ds.Tables[0].Rows[i]["PD_PAYTYPE"].ToString() != "002")
                            {
                                immediatePayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001" && ds.Tables[0].Rows[i]["PD_PAYTYPE"].ToString() == "002")
                            {
                                couponPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);

                                strSqlToUpdateBStyleDB.Append("update czkzcdmx set state = 3 where CZKBH='");
                                strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSqlToUpdateBStyleDB.Append("'|");

                                strSqlToUpdateErpDB.Append("update czkzcdmx set state = 3 where CZKBH='");
                                strSqlToUpdateErpDB.Append(ds.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSqlToUpdateErpDB.Append("'|");

                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "003")
                            {
                                accountPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else
                            {
                                continue;
                            }
                            strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=0,PD_GETAMT=0 where PD_ID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_ID"]);
                            strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        string operatorId = Share.UserValue(0);

                        //if (order.ORDER_PAYAMT > immediatePayAmount + accountPayAmount)
                        //{
                        //    strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=0,ORDER_ACHECKER='',ORDER_ACHECKDATE='");
                        //    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        //    strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=0,ORDER_CLEARAMT=ORDER_CLEARAMT-");
                        //    strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                        //    strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                        //    strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                        //    strSqlToUpdateBStyleDB.Append("'|");
                        //}
                        //else
                        //{

                        strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=0,ORDER_ACHECKER='',ORDER_ACHECKDATE=NULL");
                        strSqlToUpdateBStyleDB.Append(",ORDER_CLEAR=0,ORDER_CLEARAMT=ORDER_CLEARAMT-");
                        strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount + couponPayAmount);
                        strSqlToUpdateBStyleDB.Append(",BYZD9=NULL,Coupon=0,CouponMoney=0");
                        strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                        strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                        strSqlToUpdateBStyleDB.Append("'|");


                        new BLL.LIQUAN_CUSTOMER().DeleteCoupon(this.Code, strSqlToUpdateBStyleDB, strSqlToUpdateErpDB);
                        //}

                        Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                        if (userInfo == null)
                        {
                            Share.Alert(Page, "系统内无此会员信息！"); return;
                        }
                        Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                        if (userAccount == null)
                        {
                            Share.Alert(this.Page, "系统内无此会员的结余款信息，因此不能使用结余款支付！"); return;
                        }
                        if (accountPayAmount != 0)
                        {
                            //if (accountPayAmount > userInfo.BYZD12 + userAccount.DQJE_1)
                            //{
                            //    Share.Alert(this.Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                            //}


                            string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount, userInfo.DM);
                            strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                            string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("004", order.ORDER_ID, operatorId, operatorId, order.ORDER_CUSTOMERCODE, accountPayAmount);
                            strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);


                        }

                        if (strSqlToUpdateErpDB.ToString() == "")
                        {
                            string stringSql = strSqlToUpdateBStyleDB.ToString();
                            char[] charToTrim = new char[] { '|' };
                            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                            result = new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
                        }
                        else
                        {
                            string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                            string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                            char[] charToTrim = new char[] { '|' };
                            string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                            string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                            result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                        }
                    }
                    #endregion
                }
                else
                {
                    Share.Alert(Page, "支付金额不足"); return;
                }
                break;
            case "1":
                order.ORDER_ACHECK = 0;
                order.ORDER_ACHECKER = Share.UserValue(0);
                order.ORDER_ACHECKDATE = DateTime.Now;
                order.ORDER_LOCK = 1;
                result = new BLL.ORDERDOC().Update(order);
                break;
        }
        if (result)
        {
            Share.InsertLog("400101", "00013");
            Response.Redirect("OrderDetail.aspx?code=" + this.Code);
        }
        else
        {
            Share.Alert(Page, "财务反审核失败"); return;
        }
    }
    #endregion

    #region 作废
    protected void btnInvalid_Click(object sender, EventArgs e)
    {
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(Request.QueryString["code"].ToString().Trim());//获取订单主表
        if (order.ORDER_LOCK != 1)
        {
            Share.Alert(Page, "订单未锁定,不能操作"); return;
        }
        if (order.ORDER_LOCKER != Share.UserValue(0))
        {
            Share.Alert(Page, "由于您不是本订单的锁定人，所以无权操作!"); return;
        }
        if (order.ORDER_CHECK == 1 || order.ORDER_ACHECK == 1 || order.ORDER_SEND == 1)
        {
            Share.Alert(Page, "订单已做处理,不能作废!"); return;
        }
        if (!Check.CheckPermission("400101", "00018"))
        {
            Share.Alert(Page, "无权操作"); return;
        }
        if (((TextBox)dlistOrderMain.Items[0].FindControl("txtNote")).Text.Trim() == "")
        {
            Share.Alert(Page, "请写备注"); return;
        }
        Model.ORDERDOC od = new BLL.ORDERDOC().GetModel(this.Code);
        od.ORDER_DELETE = 1;
        od.ORDER_DELETER = Share.UserValue(0);
        od.ORDER_DELETEDATE = DateTime.Now;
        od.ORDER_NOTE = ((TextBox)dlistOrderMain.Items[0].FindControl("txtNote")).Text.Trim();
        if (new BLL.ORDERDOC().Update(od))
        {
            Share.InsertLog("400101", "00003");
            Response.Redirect("OrderList.aspx");
        }
        else
        {
            Share.Alert(Page, "保存失败"); return;
        }
    }
    #endregion

    #region 导出
    protected void btnExport_Click(object sender, EventArgs e)
    {
        //this.Code
    }
    #endregion

    #region 打印
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        string sprinttype = "0";//默认打印时不显示界面
        if (ConfigurationManager.AppSettings["PrintType"] != null && ConfigurationManager.AppSettings["PrintType"] != "") sprinttype = ConfigurationManager.AppSettings["PrintType"];
        string openurlstr = "";
        openurlstr += "window.open('../BillReport.aspx?DJBH=" + this.Code + "&ReportModule=DDGL/SDDHD&ReportName=SDDHD&PrintType=" + sprinttype + "');";
        Page.RegisterStartupScript("StartUp", "<script language=javascript>" + openurlstr + "</script>");

        //this.Code


    }
    #endregion

    #region 意见
    protected void btnSuggest_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00021"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Response.Redirect("AddSuggestion.aspx?code=" + Request.QueryString["code"].ToString().Trim());
    }
    #endregion

    #region 申请退货



    protected void btnApplyForReturnPurchase_Click(object sender, EventArgs e)
    {
        if (((CheckBox)dlistOrderMain.Items[0].FindControl("chkDeliver")).Checked)
        {
            if (new BLL.RETURNDOC().IsExistNonAuditReturnDoc(this.Code))
            {
                Share.Alert(Page, "该订单已被申请退货,并且退货单尚未财务审核!"); return;
            }
            Response.Redirect("NewReturnDoc.aspx?code=" + this.Code);
        }
        else
        {
            Share.Alert(Page, "该订单尚未发货,不允许退货！");
        }
    }
    #endregion

    #region 取消
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.RawUrl);
    }
    #endregion

    #region 返回
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("OrderList.aspx");
    }
    #endregion

    #region 结算
    protected void btnSettle_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00015"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Model.ORDERDOC od = new BLL.ORDERDOC().GetModel(this.Code);
        if (od.ORDER_CLEAR == 1)
        {
            Share.Alert(this.Page, "该订单已结算，不能再次结算！"); return;
        }
        if (od.ORDER_SEND == 0)
        {
            Share.Alert(this.Page, "该订单未发货，不能结算！"); return;
        }
        Response.Redirect("OrderClear.aspx?code=" + this.Code);
    }
    #endregion

    #region 修改支付明细
    protected void btnEditPayDetail_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00016"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        if (((CheckBox)dlistOrderMain.Items[0].FindControl("chkClear")).Checked)
        {
            Share.Alert(this.Page, "已经结算的订单不能修改支付明细。"); return;
        }
        if (new BLL.PAYDETAIL().GetNotGetPayDetailsCountByOrderId(this.Code) == 0)
        {
            Share.Alert(this.Page, "该订单的所有支付明细均以到帐，因此不能修改！"); return;
        }
        Response.Redirect("PayDetailEdit.aspx?code=" + Request.QueryString["code"].ToString());
    }
    #endregion

    #region 可用库存判断弹出框按钮事件处理



    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);

        StringBuilder sbOrderId = new StringBuilder();//支付明细中具有相同支付方式和交易号的订单
        if (order.ORDER_APAY == 0)
        {
            decimal payAmount = 0.00M;
            decimal accountPayAmount = 0.00M;
            for (int i = 0; i < this.DataTableOrderPayDetail.Rows.Count; i++)
            {
                payAmount += Convert.ToDecimal(this.DataTableOrderPayDetail.Rows[i]["pd_payamt"]);
                if (this.DataTableOrderPayDetail.Rows[i]["pd_dtcode"].ToString() == "003")
                {
                    accountPayAmount += Convert.ToDecimal(this.DataTableOrderPayDetail.Rows[i]["pd_payamt"]);
                }

                if (new BLL.PAYTYPE().GetModel(this.DataTableOrderPayDetail.Rows[i]["pd_paytype"].ToString()).PT_HAVEDEAL == 1)
                {
                    if (this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString() == "")
                    {
                        Share.Alert(Page, "请输入交易号！"); return;
                    }
                    //检查支付明细中的交易号
                    DataSet dst = new BLL.PAYDETAIL().GetPayDetailByPayTypeAndDealId(this.DataTableOrderPayDetail.Rows[i]["pd_paytype"].ToString(), this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString());
                    //检查充值单中的交易号

                    string remittanceId = "";//和订单支付明细具有相同支付方式和交易号的充值单
                    new BLL.REMITTANCE().CheckRepeat(this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString(), out remittanceId, this.DataTableOrderPayDetail.Rows[i]["pd_paytype"].ToString());

                    if (dst.Tables[0].Rows.Count > 1 && remittanceId.Length > 0)
                    {
                        sbOrderId.Append("相同交易号：" + this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString());
                        sbOrderId.Append(" 在订单：");
                        for (int j = 0; j < dst.Tables[0].Rows.Count; j++)
                        {
                            sbOrderId.Append(dst.Tables[0].Rows[j]["PD_ID"].ToString() + " ");//订单号

                        }
                        sbOrderId.Append(" 在充值单：");
                        sbOrderId.Append(remittanceId);
                        sbOrderId.Append("中存在.");
                    }
                    else if (dst.Tables[0].Rows.Count > 1 && remittanceId.Length == 0)
                    {
                        sbOrderId.Append("相同交易号：" + this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString());
                        sbOrderId.Append(" 在订单：");
                        for (int j = 0; j < dst.Tables[0].Rows.Count; j++)
                        {
                            sbOrderId.Append(dst.Tables[0].Rows[j]["PD_ID"].ToString() + " ");//订单号

                        }
                        sbOrderId.Append("中存在.");
                    }
                    else if (dst.Tables[0].Rows.Count == 1 && remittanceId.Length > 0)
                    {
                        sbOrderId.Append("相同交易号：" + this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString());
                        sbOrderId.Append(" 在充值单：");
                        sbOrderId.Append(remittanceId);
                        sbOrderId.Append("中存在.");
                    }
                    if (sbOrderId.Length > 0)
                    {
                        Share.Alert(Page, sbOrderId.ToString()); return;
                    }
   
                    /*DataSet dst = new BLL.PAYDETAIL().GetPayDetailByPayTypeAndDealId(this.DataTableOrderPayDetail.Rows[i]["pd_paytype"].ToString(), this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString());
                    if (dst.Tables[0].Rows.Count > 1)
                    {
                        string strInfo = "交易号为" + this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString() + "的支付明细与其他订单的支付明细交易号重复，请核对交易号重新输入后保存订单，并再次审核！";
                        Share.Alert(Page, strInfo); return;
                    }
                    string remittanceId = "";
                    if (new BLL.REMITTANCE().CheckRepeat(this.DataTableOrderPayDetail.Rows[i]["pd_dealid"].ToString(), out remittanceId, this.DataTableOrderPayDetail.Rows[i]["pd_paytype"].ToString()))
                    {
                        string strAlert = "订单支付明细的交易号在充值单中已经存在,所涉及到的充值单编号为:" + remittanceId + " 请核对交易号重新输入后保存订单，并再次审核！";
                        Share.Alert(Page, strAlert); return;
                    }*/
                }
            }

            if (order.ORDER_AAMT > payAmount)
            {
                Share.Alert(Page, "支付金额不足！"); return;
            }
            /*
            if (accountPayAmount > 0.00M)
            {
                Model.V_VIPSET vvs = new BLL.V_VIPSET().GetModelByGKDM(order.ORDER_CUSTOMERCODE);
                Model.V_VIP_ACCOUNT vva = new BLL.V_VIP_ACCOUNT().GetModel(vvs.DM);
                if (vva == null)
                {
                    if (0.00M + vvs.BYZD12 < accountPayAmount)
                    {
                        Share.Alert(Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                    }
                }
                else
                {
                    if (vva.DQJE_1 + vvs.BYZD12 < accountPayAmount)
                    {
                        Share.Alert(Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                    }
                }
            }
            */
        }
        if (new BLL.ORDERDOC().P_Order_Audit(0, System.Configuration.ConfigurationSettings.AppSettings["ckdm"].ToString(), System.Configuration.ConfigurationSettings.AppSettings["kwdm"].ToString(), this.Code, Share.UserValue(0)))
        {
            Share.InsertLog("400101", "00010");
            Response.Redirect("OrderDetail.aspx?code=" + this.Code);
        }
        else
        {
            Share.Alert(Page, "审批失败"); return;
        }
    }
    protected void btnCancelAudit_Click(object sender, EventArgs e)
    {
        return;
    }
    #endregion

    #region 保存方法
    private bool Save()
    {
        if (!Check.CheckPermission("400101", "00017"))
        {
            throw new Exception("无权操作");
        }
        if (dlistOrderDetail.Items.Count == 0)
        {
            throw new Exception("请选择要购买的商品");
        }
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
        if (order == null)
        {
            throw new Exception("系统无法读取到该订单");
        }

        ValidShipAddressInfo();

        FillValueIntoOrderDetailDataTable(this.DataTableOrderDetail);
        FillValueIntoOrderPayDetailDataTable(this.DataTableOrderPayDetail);

        if (((DropDownList)dlistOrderMain.Items[0].FindControl("dropPayAfterReceive")).SelectedValue == "1")
        {
            if (this.DataTableOrderPayDetail.Rows.Count > 0)
            {
                throw new Exception("货到付款订单不能有支付明细");
            }
        }

        decimal totalWeight = 0.00M;
        decimal productTotalPrice = 0.00M;
        int totalQuantity = 0;
        decimal totalPrice = 0.00M;
        decimal payAmount = 0.00M;

        for (int i = 0; i < this.DataTableOrderDetail.Rows.Count; i++)
        {
            totalWeight += Convert.ToDecimal(this.DataTableOrderDetail.Rows[i]["od_weight"]) * Convert.ToInt32(this.DataTableOrderDetail.Rows[i]["od_qty"]);
            productTotalPrice += Convert.ToDecimal(this.DataTableOrderDetail.Rows[i]["od_aamt"]);
            totalQuantity += Convert.ToInt32(this.DataTableOrderDetail.Rows[i]["od_qty"]);
        }

        totalPrice = productTotalPrice - Convert.ToDecimal(((TextBox)dlistOrderMain.Items[0].FindControl("txtOfferAmt")).Text.Trim()) + Convert.ToDecimal(((TextBox)dlistOrderMain.Items[0].FindControl("txtTranCost")).Text.Trim());

        bool isSecDeal = false;
        for (int i = 0; i < this.DataTableOrderPayDetail.Rows.Count; i++)
        {
            if (this.DataTableOrderPayDetail.Rows[i]["pd_dtcode"].ToString() == "002")
            {
                isSecDeal = true;
                //break;
            }
            payAmount += Convert.ToDecimal(this.DataTableOrderPayDetail.Rows[i]["pd_payamt"]);
        }

        bool isPromotion = false;
        if (hidOrderMainDJBH.Value == "")
        {
            for (int i = 0; i < this.DataTableOrderDetail.Rows.Count; i++)
            {
                if (this.DataTableOrderDetail.Rows[i]["od_offerid"].ToString() != "")
                {
                    isPromotion = true;
                    break;
                }
            }
        }
        else
        {
            isPromotion = true;
        }


        StringBuilder strSql = new StringBuilder();
        strSql.Append("update OrderDoc set ORDER_OFFERAMT=");
        strSql.Append(((TextBox)dlistOrderMain.Items[0].FindControl("txtOfferAmt")).Text.Trim());
        strSql.Append(",ORDER_AMT=");
        strSql.Append(productTotalPrice);
        strSql.Append(",ORDER_TAMT=");
        strSql.Append(productTotalPrice + Convert.ToDecimal(((TextBox)dlistOrderMain.Items[0].FindControl("txtTranCost")).Text.Trim()));
        strSql.Append(",ORDER_PAYAMT=");
        strSql.Append(payAmount);
        strSql.Append(",ORDER_QTY=");
        strSql.Append(totalQuantity);
        strSql.Append(",ORDER_AAMT=");
        strSql.Append(totalPrice);
        strSql.Append(",ORDER_TRANCOST=");
        strSql.Append(((TextBox)dlistOrderMain.Items[0].FindControl("txtTranCost")).Text.Trim());
        strSql.Append(",ORDER_NOTE='");
        strSql.Append(((TextBox)dlistOrderMain.Items[0].FindControl("txtNote")).Text.Trim());
        strSql.Append("',ORDER_COSTNATURE='");
        strSql.Append(((DropDownList)dlistOrderMain.Items[0].FindControl("dropCostNature")).SelectedValue);
        strSql.Append("',ORDER_OFCODE='");
        strSql.Append(((DropDownList)dlistOrderMain.Items[0].FindControl("dropOrderSource")).SelectedValue);
        strSql.Append("',ORDER_APAY=");
        strSql.Append(((DropDownList)dlistOrderMain.Items[0].FindControl("dropPayAfterReceive")).SelectedValue);
        strSql.Append(",ORDER_WEIGHT=");
        strSql.Append(totalWeight);
        strSql.Append(",ORDER_SECDEAL=");
        strSql.Append(isSecDeal ? 1 : 0);
        strSql.Append(",ORDER_TRANERCODE='");
        strSql.Append(((DropDownList)dlistOrderMain.Items[0].FindControl("dropTraner")).SelectedValue);
        if (((CheckBox)dlistOrderMain.Items[0].FindControl("chkNINV")).Checked)
        {
            strSql.Append("',ORDER_NINV=1,ORDER_INVTITLE='");
            strSql.Append(((TextBox)dlistOrderMain.Items[0].FindControl("txtINVTITLE")).Text.Trim());
        }
        else
        {
            strSql.Append("',ORDER_NINV=0,ORDER_INVTITLE='");
        }

        strSql.Append("',ORDER_GETER='");
        strSql.Append(txtReceiver.Value);
        strSql.Append("',ORDER_GETADDRESS='");
        strSql.Append(txtAddress.Value.Replace(",", " "));
        strSql.Append("',ORDER_GETPOSTCODE='");
        strSql.Append(txtPostCode.Value);
        strSql.Append("',ORDER_GETERPHONE1='");
        strSql.Append(PhoneStr);
        strSql.Append("',ORDER_GETERPHONE2='");
        strSql.Append(txtMobile.Value);
        strSql.Append("',order_Province='");
        strSql.Append(Province.Items[Province.SelectedIndex].Value);
        strSql.Append("',order_city='");
        strSql.Append(hidCityCode.Value);
        strSql.Append("',order_area='");
        strSql.Append(hidAreaCode.Value);
        strSql.Append("',ORDER_OFFERID='");
        strSql.Append(hidOrderMainDJBH.Value);
        strSql.Append("',ORDER_IsPromotion=");
        strSql.Append(isPromotion ? 1 : 0);
        if (hidIsUseStationDelivery.Value == "1")
        {
            strSql.Append(",BYZD4=");
            strSql.Append(hidServiceStationId.Value);
            strSql.Append(",BYZD5='1',BYZD6='");
            strSql.Append(hidIsPayAfterReceive.Value);
            strSql.Append("',byzd7='0'");
        }
        else if (hidIsUseStationDelivery.Value == "0")
        {
            strSql.Append(",BYZD4=0,BYZD5='0',BYZD6='0',byzd7='0'");
        }
        strSql.Append(" where order_id='");
        strSql.Append(this.Code);
        strSql.Append("'|");

        decimal pointRate = new BLL.V_VIPSET().GetBaseBS(hidCustomerId.Value);
        if (pointRate == 0)
        {
            throw new Exception("系统无法获取到该会员的积分兑换比率");
        }

        strSql.Append("delete from ORDERDETAIL where OD_ID='");
        strSql.Append(this.Code);
        strSql.Append("'|");

        for (int i = 0; i < this.DataTableOrderDetail.Rows.Count; i++)
        {
            if (this.DataTableOrderDetail.Rows[i]["OD_DISC"].ToString() == "")//|| decimal.Parse(this.DataTableOrderDetail.Rows[i]["OD_DISC"].ToString()) == 0.00M
            { throw new Exception("折扣不能为零或为空"); }
            if (this.DataTableOrderDetail.Rows[i]["OD_COLORCODE"] == "-1")
            {
                throw new Exception("请选择颜色");
            }
            if (this.DataTableOrderDetail.Rows[i]["OD_SIZECODE"] == "-1")
            {
                throw new Exception("请选择尺码");
            }
            strSql.Append("INSERT INTO ORDERDETAIL([OD_ID],[OD_DETAILID],[OD_CMDCODE],[OD_COLORCODE],[OD_SIZECODE],");
            strSql.Append("[OD_QTY],[OD_SPRICE],[OD_DISC],[OD_APRICE],[OD_SAMT],[OD_AAMT],[OD_ADDITG],[OD_WEIGHT],");
            strSql.Append("[OD_FIELD1],[OD_FIELD2],[OD_OFFERNO],[OD_OFFERID])VALUES('");
            strSql.Append(this.Code);
            strSql.Append("','");
            strSql.Append(i + 1);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_CMDCODE"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_COLORCODE"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_SIZECODE"]);
            strSql.Append("',");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_QTY"]);
            strSql.Append(",");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_SPRICE"]);
            strSql.Append(",");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_DISC"]);
            strSql.Append(",");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_APRICE"]);
            strSql.Append(",");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_SAMT"]);
            strSql.Append(",");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_AAMT"]);
            strSql.Append(",");
            strSql.Append(Convert.ToDecimal(this.DataTableOrderDetail.Rows[i]["OD_AAMT"]) * pointRate);
            strSql.Append(",");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_WEIGHT"]);
            strSql.Append(",'");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_FIELD1"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_FIELD2"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_OFFERNO"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderDetail.Rows[i]["OD_OFFERID"]);
            strSql.Append("')| ");
        }

        strSql.Append("delete from paydetail where pd_Id='");
        strSql.Append(this.Code);
        strSql.Append("'|");

        int count = 0;
        for (int i = 0; i < this.DataTableOrderPayDetail.Rows.Count; i++)
        {
            strSql.Append("Insert into PayDetail([pd_id],[pd_detailid],[pd_paytype],[pd_payamt],[pd_paydate],[pd_dealid],[pd_dealdate],[pd_account],[pd_note],[pd_dtcode])values('");
            strSql.Append(this.Code);
            strSql.Append("','");
            strSql.Append(i + 1);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_paytype"]);
            strSql.Append("',");
            strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_payamt"]);
            strSql.Append(",'");
            strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_paydate"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_dealid"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_dealdate"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_account"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_note"]);
            strSql.Append("','");
            strSql.Append(this.DataTableOrderPayDetail.Rows[i]["pd_dtcode"]);
            strSql.Append("')|");

            count++;
        }

        for (int i = 0; i < dlistCoupon.Items.Count; i++)
        {
            strSql.Append("update LIQUAN_CUSTOMER set frozen=0 where CouponCode='");
            strSql.Append(((Label)dlistCoupon.Items[i].FindControl("lblCouponCode")).Text);
            strSql.Append("' and CustomerCode='");
            strSql.Append(order.ORDER_CUSTOMERCODE);
            strSql.Append("'|");
            if (((CheckBox)dlistCoupon.Items[i].FindControl("chkCoupon")).Checked)
            {
                strSql.Append("Insert into PayDetail([pd_id],[pd_detailid],[pd_paytype],[pd_payamt],[pd_paydate],[pd_dealid],[pd_dealdate],[pd_account],[pd_note],[pd_dtcode])values('");
                strSql.Append(this.Code);
                strSql.Append("','");
                strSql.Append(++count);
                strSql.Append("','002',");
                strSql.Append(((Label)dlistCoupon.Items[i].FindControl("lblCouponAmount")).Text);
                strSql.Append(",'");
                strSql.Append(DateTime.Now);
                strSql.Append("','");
                strSql.Append(((Label)dlistCoupon.Items[i].FindControl("lblCouponCode")).Text);
                strSql.Append("','");
                strSql.Append(DateTime.Now);
                strSql.Append("','");
                strSql.Append(order.ORDER_CUSTOMERCODE);
                strSql.Append("','','001')|");

                strSql.Append("update LIQUAN_CUSTOMER set frozen=1 where CouponCode='");
                strSql.Append(((Label)dlistCoupon.Items[i].FindControl("lblCouponCode")).Text);
                strSql.Append("' and CustomerCode='");
                strSql.Append(order.ORDER_CUSTOMERCODE);
                strSql.Append("'|");
            }
        }
        string stringSql = strSql.ToString();
        char[] charToTrim = new char[] { '|' };
        string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
        if (new SQLServerDAL.ORDERDETAIL().UpdateOrderDetailAndOrderMain(sqlCommandArray))
        {
            Share.InsertLog("400101", "00017");
            BindDataListOrderMain();
            return true;
        }
        else
        {
            return false;
        }
    }
    #endregion

    #region 财务审核方法
    private void FinancialAffairsAudit()
    {
        if (!Check.CheckPermission("400101", "00012"))
        {
            Share.Alert(Page, "无权操作"); return;
        }

        bool result = false;

        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(Request.QueryString["code"].ToString().Trim());//获取订单主表

        switch (order.ORDER_APAY.ToString())
        {
            case "0"://非货到付款




                DataSet ds = new BLL.PAYDETAIL().P_Order_GetProductZFMX(this.Code);//获取订单支付明细
                decimal payAmount = 0.00M;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    payAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["pd_payamt"]);
                }
                if (order.ORDER_AAMT <= payAmount)
                {


                    #region 含担保交易




                    if (order.ORDER_SECDEAL == 1)
                    {
                        decimal immediatePayAmount = 0.00M;
                        decimal accountPayAmount = 0.00M;
                        StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                        StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001")
                            {
                                immediatePayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "003")
                            {
                                accountPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else
                            {
                                continue;
                            }
                            strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=1,PD_GETAMT=");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            strSqlToUpdateBStyleDB.Append(",PD_GETDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("' where PD_ID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_ID"]);
                            strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        string operatorId = Share.UserValue(0);

                        //if (order.ORDER_PAYAMT <= immediatePayAmount + accountPayAmount)
                        //{
                        //    strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                        //    strSqlToUpdateBStyleDB.Append(operatorId);
                        //    strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                        //    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        //    strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                        //    strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                        //    strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                        //    strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                        //    strSqlToUpdateBStyleDB.Append("'|");
                        //}
                        //else
                        //{
                        strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                        strSqlToUpdateBStyleDB.Append(operatorId);
                        strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                        strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        strSqlToUpdateBStyleDB.Append("',ORDER_CLEARAMT=ORDER_CLEARAMT+");
                        strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                        strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                        strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                        strSqlToUpdateBStyleDB.Append("'|");
                        //}

                        Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                        if (userInfo == null)
                        {
                            Share.Alert(Page, "系统内无此会员信息！"); return;
                        }
                        Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                        if (userAccount == null)
                        {
                            strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateBStyleDB.Append(userInfo.DM);
                            strSqlToUpdateBStyleDB.Append("',0)|");

                            strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateErpDB.Append(userInfo.DM);
                            strSqlToUpdateErpDB.Append("',0)|");
                        }
                        if (accountPayAmount != 0)
                        {
                            if (accountPayAmount > userInfo.BYZD12 + userAccount.DQJE_1)
                            {
                                Share.Alert(this.Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                            }


                            string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount * -1, userInfo.DM);
                            strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                            string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("003", order.ORDER_ID, operatorId, operatorId, order.ORDER_CUSTOMERCODE, accountPayAmount * -1);
                            strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);

                        }

                        if (strSqlToUpdateErpDB.ToString() == "")
                        {
                            string stringSql = strSqlToUpdateBStyleDB.ToString();
                            char[] charToTrim = new char[] { '|' };
                            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                            result = new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
                        }
                        else
                        {
                            string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                            string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                            char[] charToTrim = new char[] { '|' };
                            string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                            string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                            result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                        }
                    }
                    #endregion
                    #region 不含担保交易
                    else
                    {
                        decimal immediatePayAmount = 0.00M;
                        decimal accountPayAmount = 0.00M;
                        StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                        StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "001")
                            {
                                immediatePayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "003")
                            {
                                accountPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            }
                            else
                            {
                                continue;
                            }
                            //strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=1,PD_GETAMT=");
                            //strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            //strSqlToUpdateBStyleDB.Append(" where PD_ID='");
                            //strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_ID"]);
                            //strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                            //strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                            //strSqlToUpdateBStyleDB.Append("'|");

                            strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=1,PD_GETAMT=");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_PAYAMT"]);
                            strSqlToUpdateBStyleDB.Append(",PD_GETDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("' where PD_ID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_ID"]);
                            strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        string operatorId = Share.UserValue(0);

                        if (order.ORDER_PAYAMT <= immediatePayAmount + accountPayAmount)
                        {
                            strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                            strSqlToUpdateBStyleDB.Append(operatorId);
                            strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                            strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                            strSqlToUpdateBStyleDB.Append(",BYZD9='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                            strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                            strSqlToUpdateBStyleDB.Append("'|");
                        }
                        else
                        {
                            strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                            strSqlToUpdateBStyleDB.Append(operatorId);
                            strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("',ORDER_CLEARAMT=ORDER_CLEARAMT+");
                            strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                            strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                            strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString().Trim());
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                        if (userInfo == null)
                        {
                            Share.Alert(Page, "系统内无此会员信息！"); return;
                        }
                        Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                        if (userAccount == null)
                        {
                            strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateBStyleDB.Append(userInfo.DM);
                            strSqlToUpdateBStyleDB.Append("',0)|");

                            strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateErpDB.Append(userInfo.DM);
                            strSqlToUpdateErpDB.Append("',0)|");
                        }
                        if (accountPayAmount != 0)
                        {
                            if (accountPayAmount > userInfo.BYZD12 + userAccount.DQJE_1)
                            {
                                Share.Alert(this.Page, "结余款支付金额超出了结余款和信用额度之和，因此不能使用结余款支付！"); return;
                            }


                            string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount * -1, userInfo.DM);
                            strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                            string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("003", order.ORDER_ID, operatorId, operatorId, order.ORDER_CUSTOMERCODE, accountPayAmount * -1);
                            strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);

                        }

                        if (strSqlToUpdateErpDB.ToString() == "")
                        {
                            string stringSql = strSqlToUpdateBStyleDB.ToString();
                            char[] charToTrim = new char[] { '|' };
                            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                            result = new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
                        }
                        else
                        {
                            string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                            string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                            char[] charToTrim = new char[] { '|' };
                            string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                            string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                            result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                        }
                    }
                    #endregion
                }
                else
                {
                    Share.Alert(Page, "支付金额不足"); return;
                }
                break;

            case "1":
                order.ORDER_ACHECK = 1;
                order.ORDER_ACHECKER = Share.UserValue(0);
                order.ORDER_ACHECKDATE = DateTime.Now;

                result = new BLL.ORDERDOC().Update(order);
                break;
        }
        if (result)
        {
            Share.InsertLog("400101", "00012");
            Response.Redirect("OrderDetail.aspx?code=" + this.Code);
        }
        else
        {
            Share.Alert(Page, "财务审核失败"); return;
        }
    }
    #endregion

    #region 检查配送地址非空
    private void ValidShipAddressInfo()
    {
        if (txtReceiver.Value == "")
        {
            throw new Exception("请填写收货人姓名！");
        }
        if (txtAddress.Value == "")
        {
            throw new Exception("请填写地址！");
        }
        if (txtPostCode.Value == "")
        {
            throw new Exception("请填写固定邮政编码！");
        }
        Regex regexPostCode = new Regex("^[0-9]\\d{5}$");
        if (!regexPostCode.IsMatch(txtPostCode.Value))
        {
            throw new Exception("请输入正确的6位数邮政编码！");
        }

        if ((txtPhone1.Value.Length == 0 || txtPhone1.Value == "号码") && txtMobile.Value.Length == 0)
        {
            throw new Exception("手机或固定电话必填一个");
        }

        if (txtPhone.Value.Length > 0 && txtPhone.Value != "区号" || txtPhone1.Value.Length > 0 && txtPhone1.Value != "号码" || txtPhone2.Value.Length > 0 && txtPhone2.Value != "分机")
        {
            if ((txtPhone.Value.Length > 0 && txtPhone.Value != "区号") || (txtPhone1.Value.Length > 0 && txtPhone1.Value != "号码"))
            {

                PhoneStr = txtPhone.Value + "-" + txtPhone1.Value;
                Regex reg = new Regex("^\\d{3,4}$");//检查区号


                Regex reg1 = new Regex("^\\d{7,8}$");//检查电话号码


                if (!reg.IsMatch(txtPhone.Value) || !reg1.IsMatch(txtPhone1.Value))
                {
                    throw new Exception("固定电话格式错误");
                }
            }
            if (txtPhone2.Value.Length > 0 && txtPhone2.Value != "分机")
            {
                PhoneStr = txtPhone.Value + "-" + txtPhone1.Value + "-" + txtPhone2.Value;

                Regex reg = new Regex("^\\d{3,4}$");//检查区号


                Regex reg1 = new Regex("^\\d{7,8}$");//检查电话号码


                Regex reg2 = new Regex("^\\d{1,5}$");//检查分机号
                if (!reg.IsMatch(txtPhone.Value) || !reg1.IsMatch(txtPhone1.Value) || !reg2.IsMatch(txtPhone2.Value))
                {
                    throw new Exception("固定电话格式错误");
                }
            }
        }
        if (txtMobile.Value.Length > 0)
        {
            Regex reg = new Regex("^\\d+$");//检查手机


            if (!reg.IsMatch(txtMobile.Value))
            {
                throw new Exception("请输入正确的手机号码");
            }
        }


        //if (Province.SelectedIndex == 0)
        //{
        //    return false;
        //}
        //if (City.SelectedIndex == 0)
        //{
        //    return false;
        //}
        //if (Area.SelectedIndex == 0)
        //{
        //    return false;
        //}

    }

    private void ValidShipAddressInfo(string receiver, string address, string phone, string postCode, string mobile)
    {
        if (receiver == "")
        {
            throw new Exception("请填写收货人姓名！");
        }
        if (address == "")
        {
            throw new Exception("请填写地址！");
        }

        if (postCode == "")
        {
            throw new Exception("请填写固定邮政编码！");
        }
        Regex regexPostCode = new Regex("^[0-9]\\d{5}$");
        if (!regexPostCode.IsMatch(postCode))
        {
            throw new Exception("请输入正确的6位数邮政编码！");
        }
        //if (phone == "")
        //{
        //    throw new Exception("请填写固定电话号码！");
        //}
        //if (mobile == "")
        //{
        //    throw new Exception("请填写手机号码！");
        //}
        if (phone == "" && mobile == "")
        {
            throw new Exception("固定电话和手机必须至少填写一项！");
        }
        if (phone.Length > 0)
        {
            string[] phoneArr = phone.Split('|');

            if (phoneArr.Length == 2)
            {
                PhoneStr = phoneArr[0] + "-" + phoneArr[1];

                Regex reg = new Regex("^\\d{3,4}$");//检查区号


                Regex reg1 = new Regex("^\\d{7,8}$");//检查电话号码


                if (!reg.IsMatch(phoneArr[0]) || !reg1.IsMatch(phoneArr[1]))
                {
                    throw new Exception("固定电话格式错误");
                }
            }
            if (phoneArr.Length == 3)
            {
                PhoneStr = phoneArr[0] + "-" + phoneArr[1] + "-" + phoneArr[2];

                Regex reg = new Regex("^\\d{3,4}$");//检查区号


                Regex reg1 = new Regex("^\\d{7,8}$");//检查电话号码


                Regex reg2 = new Regex("^\\d{1,5}$");//检查分机号
                if (!reg.IsMatch(phoneArr[0]) || !reg1.IsMatch(phoneArr[1]) || !reg2.IsMatch(phoneArr[2]))
                {
                    throw new Exception("固定电话格式错误");
                }
            }
        }
        if (mobile.Length > 0)
        {
            Regex reg = new Regex("^\\d+$");//检查手机


            if (!reg.IsMatch(mobile))
            {
                throw new Exception("请输入正确的手机号码");
            }
        }


        //if (Province.SelectedIndex == 0)
        //{
        //    return false;
        //}
        //if (City.SelectedIndex == 0)
        //{
        //    return false;
        //}
        //if (Area.SelectedIndex == 0)
        //{
        //    return false;
        //}
    }

    #endregion

    #endregion

    #region 按钮状态设置



    private void SetPropertyOfButtons()
    {
        if (!((CheckBox)dlistOrderMain.Items[0].FindControl("chkLock")).Checked)
        {
            btnUnlock.Enabled = false;
            btnSave.Enabled = false;
            btnAudit.Enabled = false;
            btnAntiAudit.Enabled = false;
            btnFinancialAffairsAudit.Enabled = false;
            btnFinancialAffairsAntiAudit.Enabled = false;
            btnInvalid.Enabled = false;

            dlistOrderMain.Enabled = false;/////////////////
            dlistOrderDetail.Enabled = false;////////////////
            dlistPayDocPayDetail.Enabled = false;////////////////
            dlistReceiveAddress.Enabled = false;/////////////////
            BindDataListCoupon("lock");
            Province.Disabled = true;
            City.Disabled = true;
            Area.Disabled = true;
            pnlSendInfo.Enabled = false;
            btnAddProduct.Enabled = false;
            btnAddPayDetail.Enabled = false;
            pnlServiceStation.Enabled = false;
            hidIsOpenQueryStockWindow.Value = "0";
            //SetDeleteButtonVisibleProperty(dlistOrderDetail, "btnDelete", false);
            //SetDeleteButtonVisibleProperty(dlistPayDocPayDetail, "btnDelete", false);
        }
        else
        {
            btnLock.Enabled = false;
            btnAddProduct.Enabled = true;
            btnAddPayDetail.Enabled = true;
            SetDeleteButtonVisibleProperty(dlistOrderDetail, "btnDelete", true);
            SetDeleteButtonVisibleProperty(dlistPayDocPayDetail, "btnDelete", true);
        }
        if (!((CheckBox)dlistOrderMain.Items[0].FindControl("chkAudit")).Checked)
        {
            btnAntiAudit.Enabled = false;
            btnFinancialAffairsAudit.Enabled = false;
            BindDataListCoupon("notAudit");
        }
        else
        {
            btnSave.Enabled = false;
            btnAudit.Enabled = false;
            btnAntiAudit.Enabled = true;
            btnFinancialAffairsAudit.Enabled = true;
            btnFinancialAffairsAntiAudit.Enabled = false;
            btnInvalid.Enabled = false;

            dlistOrderMain.Enabled = false;/////////////////
            dlistOrderDetail.Enabled = false;////////////////
            dlistPayDocPayDetail.Enabled = false;////////////////
            dlistReceiveAddress.Enabled = false;/////////////////
            Province.Disabled = true;
            City.Disabled = true;
            Area.Disabled = true;
            pnlSendInfo.Enabled = false;
            btnAddProduct.Enabled = false;
            btnAddPayDetail.Enabled = false;
            pnlServiceStation.Enabled = false;
            //SetDeleteButtonVisibleProperty(dlistOrderDetail, "btnDelete", false);
            //SetDeleteButtonVisibleProperty(dlistPayDocPayDetail, "btnDelete", false);
            hidIsOpenQueryStockWindow.Value = "0";
            BindDataListCoupon("isAudit");
        }

        if (((CheckBox)dlistOrderMain.Items[0].FindControl("chkFinancialAffairsAudit")).Checked)
        {
            btnLock.Enabled = false;
            btnSave.Enabled = false;
            btnAudit.Enabled = false;
            btnAntiAudit.Enabled = false;
            btnFinancialAffairsAudit.Enabled = false;
            btnFinancialAffairsAntiAudit.Enabled = true;
            btnInvalid.Enabled = false;

            dlistOrderMain.Enabled = false;/////////////////
            dlistOrderDetail.Enabled = false;////////////////
            dlistPayDocPayDetail.Enabled = false;////////////////
            dlistReceiveAddress.Enabled = false;/////////////////
            Province.Disabled = true;
            City.Disabled = true;
            Area.Disabled = true;
            pnlSendInfo.Enabled = false;
            btnAddProduct.Enabled = false;
            btnAddPayDetail.Enabled = false;
            pnlServiceStation.Enabled = false;
            hidIsOpenQueryStockWindow.Value = "0";
            //SetDeleteButtonVisibleProperty(dlistOrderDetail, "btnDelete", false);
            //SetDeleteButtonVisibleProperty(dlistPayDocPayDetail, "btnDelete", false);
        }
        else
        {
            btnFinancialAffairsAntiAudit.Enabled = false;
        }
        if (((CheckBox)dlistOrderMain.Items[0].FindControl("chkDeliver")).Checked)
        {
            btnLock.Enabled = false;
            btnUnlock.Enabled = false;
            btnSave.Enabled = false;
            btnAudit.Enabled = false;
            btnAntiAudit.Enabled = false;
            btnFinancialAffairsAudit.Enabled = false;
            btnFinancialAffairsAntiAudit.Enabled = false;
            btnInvalid.Enabled = false;
            btnEditPayDetail.Enabled = true;

            Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);//获取订单主表
            if (order.ORDER_APAY == 0 && order.ORDER_SECDEAL == 1 && order.ORDER_CLEAR == 0)
            {//非货到付款，含担保交易，未结算的订单
                btnModifyAndClear.Visible = true;
            }
        }
        if (((CheckBox)dlistOrderMain.Items[0].FindControl("chkDelete")).Checked)
        {
            btnLock.Enabled = false;
            btnUnlock.Enabled = false;
            btnSave.Enabled = false;
            btnAudit.Enabled = false;
            btnAntiAudit.Enabled = false;
            btnFinancialAffairsAudit.Enabled = false;
            btnFinancialAffairsAntiAudit.Enabled = false;
            btnInvalid.Enabled = false;

            dlistOrderMain.Enabled = false;/////////////////
            dlistOrderDetail.Enabled = false;////////////////
            dlistPayDocPayDetail.Enabled = false;////////////////
            dlistReceiveAddress.Enabled = false;/////////////////
            Province.Disabled = true;
            City.Disabled = true;
            Area.Disabled = true;
            pnlSendInfo.Enabled = false;
            btnAddProduct.Enabled = false;
            btnAddPayDetail.Enabled = false;
            pnlServiceStation.Enabled = false;
            hidIsOpenQueryStockWindow.Value = "0";
            //SetDeleteButtonVisibleProperty(dlistOrderDetail, "btnDelete", false);
            //SetDeleteButtonVisibleProperty(dlistPayDocPayDetail, "btnDelete", false);
            BindDataListCoupon("delete");
        }

        if (((HtmlInputHidden)dlistOrderMain.Items[0].FindControl("hidPayAfterReceive")).Value == "1")
        {
            btnSettle.Visible = true;
            btnAddPayDetail.Enabled = false;
            btnSettle.Enabled = false;
            if (!((CheckBox)dlistOrderMain.Items[0].FindControl("chkClear")).Checked)
            {
                BindDataListCoupon("payAfterReceive");
                btnSettle.Enabled = true;
            }

        }
        if (this.IsUseServiceStation)
        {
            pnlServiceStation.Visible = true;
        }
        else
        {
            pnlServiceStation.Visible = false;
        }
    }

    private void SetDeleteButtonVisibleProperty(DataList dlist, string buttonId, bool isVisible)
    {
        for (int i = 0; i < dlist.Items.Count; i++)
        {
            ((Button)dlist.Items[i].FindControl(buttonId)).Enabled = isVisible;
        }
    }
    private void BindOrderNote()
    {
        DataSet dst = new BLL.ORDERNOTE().GetOrderNoteById(this.Code);
        ORDERNOTEListControl1.Bind(dst);
    }
    #endregion


    protected void btnAddSuggestion_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00021"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Response.Redirect("AddSuggestion.aspx?code=" + this.Code + "&stCode=" + this.OrderStateTypeCode);

    }
    protected void btnMerge_Click(object sender, EventArgs e)
    {
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(Code);
        if (order.ORDER_LOCK == 0)
        {
            Share.Alert(this.Page, "请先将此订单锁定再操作"); return; 
        }
        if (order.ORDER_CHECK == 1)
        {
            Share.Alert(this.Page, Code+"已经审核不能合并"); return; 
        }
        int ret = new BLL.ORDERDOC().MergeOrders(Code, hdOrder.Value);
        if (ret > 0)
        {
            //Share.Alert(this.Page, "成功");
            Response.Redirect(string.Format("OrderDetail.aspx?code={0}",Code), true);
        }
        Share.Alert(this.Page, "失败"); return;
    }

    protected void btnModifyAndClear_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00042"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Model.ORDERDOC od = new BLL.ORDERDOC().GetModel(this.Code);
        if (od.ORDER_CLEAR ==1 )
        {
            Share.Alert(this.Page, "该订单已结算，不能再次结算！"); return;
        }
        Response.Redirect("ModifyAndClear.aspx?code=" + this.Code);

    }
}
